setOnClickListener closes Android Application - java

I'm learning now Java with a book "Learning Java by building Android Games" from Packt Publishers by John Horton. I'm really newbie to OOP and I have learned C for one year. I do everything as it is in the book. After I have added setOnClickListener and tried to test my App, I see "the application was closed" instead running new Activity.
Could you please help me to find out what is wrong? The book is a little bit out of a date (Jan 2015) and I had to correct some initial code to make initial errors disappear.
package com.packtpub.mathgame;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.util.Log;
public class MainActivity extends Activity implements View.OnClickListener {
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
Log.d(TAG, "onCreate() Restoring previous state");
/* restore state */
} else {
Log.d(TAG, "onCreate() No saved state available");
/* initialize app */
}
final Button buttonPlay = (Button)findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Intent i;
i = new Intent(this, GameActivity.class);
startActivity(i);
}
}
===============
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play"
android:id="#+id/buttonPlay"
android:layout_marginTop="28dp"
android:layout_below="#+id/imageView"
android:layout_alignRight="#+id/button2"
android:layout_alignEnd="#+id/button2"
android:layout_alignLeft="#+id/button2"
android:layout_alignStart="#+id/imageView" />

1) You need to register the GameActivity In you AndroidManifest.xml like this
<activity
android:name=".GameActivity" />
inside the application tag
Just a note if these views arn't available your layout will look very wierd ;)
android:layout_below="#+id/imageView"
android:layout_alignRight="#+id/button2"
android:layout_alignEnd="#+id/button2"
android:layout_alignLeft="#+id/button2"
android:layout_alignStart="#+id/imageView"

Did you register GameActivity in your AndroidManifest.xml file ?

You should getId of your button onClick method only thn you can identity on which button you have click on , now you one
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.buttonPlay:
//write your implementation here
Toast.makeText(this, "dsfdf", Toast.LENGTH_LONG).show();
break;
case R.id.buttonPlay1:
Toast.makeText(this, "sdsdsdsd", Toast.LENGTH_LONG).show();
break;
}
}

change this:
final Button buttonPlay = (Button)findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Intent i;
i = new Intent(this, GameActivity.class);
startActivity(i);
}
in this:
final Button buttonPlay = (Button)findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i;
i = new Intent(this, GameActivity.class);
startActivity(i);
}
});

Related

Issues playing audio/sound when pressing button in android studio

Pretty new to android world, I am having an issue playing audio when clicking a button. The interesting/weird aspect of it is that same code works on my mainactivity but not on secondactivity that I have set up. I am using the same exact code that works on mainactivity. I used that code on mainactivity just to test it, keep in mind no media player has been declared or defined in mainactivity. I did that just to test to see if code works.
Here is my xml:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="15sp"
android:layout_marginBottom="15sp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="press button to play audio"
android:textSize="40sp"
android:textColor="#ffff"
android:fontFamily="cursive"
android:textStyle="bold"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginBottom="10sp"
android:layout_gravity="center"
>
<Button
android:id="#+id/AudioButton"
android:layout_width="wrap_content"
android:layout_height="50sp"
android:text="play"
android:textSize="22sp"
android:textColor="#ffff"
android:layout_marginRight="10dp"
/>
</LinearLayout>
Here is JAVA:
package nameiscleared;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Button start = (Button) findViewById(R.id.AudioButton);
start.setOnClickListener(new View.OnClickListener() {
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.audioname);
#Override
public void onClick(View view) {
mp.start();
}
});
}
}
It just my assumption, I think you are not releasing the MediaPlayer when you use it in MainActivity. That is why it is not working on secondActivity. Another mistake is, MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.audioname); need to be in onClick, not in View.OnClickListener() bracket. You need to keep in mind that after you used MediaPlayer, you need to release it when it is no longer being used.
A MediaPlayer can consume valuable system resources. Therefore, you should always take extra precautions to make sure you are not hanging on to a MediaPlayer instance longer than necessary. When you are done with it, you should always call release() to make sure any system resources allocated to it are properly released. For example, if you are using a MediaPlayer and your activity receives a call to onStop(), you must release the MediaPlayer, because it makes little sense to hold on to it while your activity is not interacting with the user (unless you are playing media in the background, which is discussed in the next section). When your activity is resumed or restarted, of course, you need to create a new MediaPlayer and prepare it again before resuming playback - Android Developers documentation.
The correct implementation supposed to be like this;
MainActivity
public class MainActivity extends AppCompatActivity{
private Button playBtn, startActivityBtn;
private MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playBtn = (Button)findViewById(R.id.playBtn);
playBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mediaPlayer = MediaPlayer.create(MainActivity.this, Settings.System.DEFAULT_RINGTONE_URI);
mediaPlayer.start();
}
});
startActivityBtn = (Button)findViewById(R.id.startActivity);
startActivityBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
});
}
#Override
protected void onStop() {
super.onStop();
if(null != mediaPlayer){
if(mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
}
SecondActivity
public class SecondActivity extends AppCompatActivity {
private Button playBtn;
private MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_econd);
playBtn = (Button)findViewById(R.id.playBtn);
playBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mediaPlayer = MediaPlayer.create(SecondActivity.this, Settings.System.DEFAULT_RINGTONE_URI);
mediaPlayer.start();
}
});
}
#Override
protected void onStop() {
super.onStop();
if(null != mediaPlayer){
if(mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
}
I am not including the layout because both of the layout are very simple. MainActivity has two button, to play and to start another activity. SecondActivity has only play button.

findViewById from different layout/xml file Android Studio

I'm trying to create a settings page for my app which has the radioGroup for 3 options to help users change the colour of the text in differrent layout/xml file. But in mysettings page I cant call the view from different layout, any idea?
Below are my codes:
Settings.Java
package com.example.sunny.mynote;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.EditText;
/**
* Created by Sunny on 19/04/2015.
*/
public class Settings extends Activity {
private RadioGroup RadioGroup1;
private RadioButton rdbRed, rdbBlue, rdbOrange;
private Button btnSave;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
RadioGroup1 = (RadioGroup) findViewById(R.id.RadioGroup1);
RadioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId == R.id.rdbRed)
{
Toast.makeText(getApplicationContext(), "choice: Red",
Toast.LENGTH_SHORT).show();
}
else if(checkedId == R.id.rdbBlue)
{
Toast.makeText(getApplicationContext(), "choice: Blue",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "choice: Orange",
Toast.LENGTH_SHORT).show();
}
}
});
rdbRed = (RadioButton) findViewById(R.id.rdbRed);
rdbBlue = (RadioButton) findViewById(R.id.rdbBlue);
rdbOrange = (RadioButton) findViewById(R.id.rdbOrange);
editText = (EditText) findViewById(R.id.editText);
btnSave = (Button)findViewById(R.id.btn_Save);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int selectedId = RadioGroup1.getCheckedRadioButtonId();
if(selectedId == rdbRed.getId()) {
//textView.setText("You chose 'Sound' option");
} else if(selectedId == rdbBlue.getId()) {
//textView.setText("You chose 'Vibration' option");
} else {
//textView.setText("You chose 'Silent' option");
}
finish();
}
});
}
#Override
public void onBackPressed() {
}
}
and I want to FindViewbyID from this layout, an EditText from this view to be exactly
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<EditText
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/noteText"
android:singleLine="false"
android:gravity="top"
android:inputType="textImeMultiLine"
android:layout_alignParentBottom="true" />
</RelativeLayout>
I think you can create an intent with extras like this:
Intent i=new Intent(context,Class.class);
i.putExtra("ColorChoice",color);
And then extract this data from your main class with:
intent.getStringExtra("ColorChoice");
You cannot do that in your Settings.java activity if your editText is not in this activity.
You can either use intent with putExtra and getExtra like #user3624383 mentioned. (more on this here)
Or a better way would be to use SharedPreferences to save your settings even if the user exits your app and return to it later

Want to create a menu for my Game Java eclipse

Hi I currently made a game and just wish to add a simple menu for it, the are two buttons on the main menu was says English and the Other says French I have managed to get the English button working which takes me to my EnglishVersion.class but I cant seem to get my French button to work. can any one help please.
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
public class MainMenu extends Activity {
Button English;
Button French;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
addListenerOnButton();
}
public void addListenerOnButton(){
final Context context = this;
English = (Button) findViewById(R.id.engbtn);
French = (Button) findViewById(R.id.frenbtn);
English.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, EnglishVersion.class);
startActivity(intent);
}
});
}
I have tried to do this and getting and im getting an error
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
public class MainMenu extends Activity {
Button English;
Button French;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
English.setOnClickListener(mButtonClickListener);
French.setOnClickListener(mButtonClickListener);
}
private View.OnClickListener mButtonClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
if (view.getId()==R.id.engbtn) {
Intent intent = new Intent(context, EnglishVersion.class);
startActivity(intent);
} else if (view.getId()==R.id.frenbtn) {
Intent intent = new Intent(context, FrenchVersion.class);
startActivity(intent);
}
}
}
}
add this:
French.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, FrenchVersion.class);
startActivity(intent);
}
});
By the way, it's not a good way to do the internationalization.
Try to read little about it here
Supporting Different Languages
You can just create various files strings-XX.XML in your res/ directory, where XX is given language symbol like FR or EN. It will even work with your default one. So if phone user has French defined as a language, your application will take it as its.
Either use the onClick property in XML like this (for both buttons);
<Button
android:id="#+id/engbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"/>
<Button
android:id="#+id/frenbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"/>
then populate the onClick method in the activity;
public void onClick(View view) {
if (view.getId()==R.id.engbtn) {
//do something
} else if (view.getId()==R.id.frenbtn) {
//do something else
}
}
OR set the onClickListeners for both button like this;
English.setOnClickListener(mButtonClickListener);
French.setOnClickListener(mButtonClickListener);
and then define the shared click listener;
private View.OnClickListener mButtonClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
if (view.getId()==R.id.engbtn) {
//do something
} else if (view.getId()==R.id.frenbtn) {
//do something else
}
}
}
Hope this helps!

Multiple ImageButtons with setOnClickListener (clicks but does not launch activities)

I have managed to successfully start two activities using the ImageButton along with .setOnClickListener tied to it, i have also included layouts with different ImageButtons. Each button launches an activity. I have created the activities. I have also managed to remover crash bugs, lint errors, have the latest Android SDK. However now the buttons stop working even though you hear the click. Neither the activity launches on the first imageButton nor the second one.
This happens the moment i put multiple ImageButtons in. It works with 1 button. I suspect the (this) command in the class is confused as to what to call. My intent call method to start new activities are streamlined and basic for quick, uncomplicated access.
Can someone please help me as to why the multiple setOnclickListener cannot be tied to the relevant imageButtons please?
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.content.Intent;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
public class MainActivity extends ActionBarActivity implements OnClickListener {
ImageButton imageButton1;
ImageButton imageButton2;
ImageButton imageButton3;
ImageButton imageButton4;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reusable_layout);
imageButton1=(ImageButton)findViewById(R.id.imageButton1);
imageButton2=(ImageButton)findViewById(R.id.imageButton2);
imageButton3=(ImageButton)findViewById(R.id.imageButton3);
imageButton4=(ImageButton)findViewById(R.id.imageButton4);
imageButton1.setOnClickListener(this);
imageButton2.setOnClickListener(this);
imageButton3.setOnClickListener(this);
imageButton4.setOnClickListener(this);
}
public void onClick1(View view) {
Intent intent =
new Intent(this, OtherActivity.class);
startActivity(intent);
}
public void onClick2(View view) {
Intent intent =
new Intent(this, OtherActivity2.class);
startActivity(intent);
}
If you notice I have only coded 2 of the four buttons (so once this code works in theory the others should).
This is what OtherActivity from imageButton1 calls.
package com.example.startanotheractivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
public class OtherActivity extends Activity
implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.other_layout);
Intent intent = getIntent();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
and this is the activity imageButton2 calls
package com.example.startanotheractivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
public class OtherActivity2 extends Activity
implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.other_layout_2);
Intent intent = getIntent();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Here is my layout.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:background="#FFFFFF" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:orientation="vertical" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="566dp"
android:layout_height="456dp"
android:background="#null"
android:src="#drawable/gatanga1"
android:onClick="onClick1" />
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="540dp"
android:layout_height="189dp"
android:background="#null"
android:src="#drawable/gatanga2"
android:onClick="onClick2" />
<ImageButton
android:id="#+id/imageButton3"
android:layout_width="540dp"
android:layout_height="189dp"
android:background="#null"
android:src="#drawable/gatanga3"
android:onClick="onClick3" />
<ImageButton
android:id="#+id/imageButton4"
android:layout_width="540dp"
android:layout_height="189dp"
android:background="#null"
android:src="#drawable/gatanga4"
android:onClick="onClick4" />
</LinearLayout>
Thank you
Many many thanks.
use a switch statement in onClick method
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.imageButton1: /** Start a new Activity OtherActivity.java */
Intent intent = new Intent(MainActivity.this, MyCards.class);
this.startActivity(intent);
break;
case R.id.imageButton2: /** Start a new Activity OtherActivity2.java */
Intent intent2 = new Intent(MainActivity.this, OtherActivity2.class);
this.startActivity(intent2);
break;
}
The onClick method passes the clicked view as an variable, you can use a switch statement to determine which view was clicked and then you can perform your operations..
public void onClick(View v) {
switch(v.getId()){
case R.id.imageButton1:
Intent intent = new Intent(MainActivity.this, OtherActivity.class);
startActivity(intent);
break;
case R.id.imageButton2:
Intent intent = new Intent(MainActivity.this, OtherActivity2.class);
startActivity(intent2);
break;
}
}
Scholars, Educated Aristocrats and of course Plumbers.
Thank you for replying. It works now by the code i did, although i will try the above solutions. I have experimented with switches and i do like them. I want to make sure memory management and file sizes are kept to a minimum as the end app will have about 40 activities.
However the way i did it was i removed all the other ImageButtons declarations in MainActivity except:
public class MainActivity extends ActionBarActivity implements OnClickListener {
ImageButton imageButton1;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reusable_layout);
imageButton1=(ImageButton)findViewById(R.id.imageButton1);
}
The onClick methods then were left as onClick1,onClick2. Both activities worked. I added onClick3 and onClick4 like the below:
public void onClick1(View view) {
Intent intent =
new Intent(this, OtherActivity.class);
startActivity(intent);
}
public void onClick2(View view) {
Intent intent =
new Intent(this, OtherActivity2.class);
startActivity(intent);
}
public void onClick3(View view) {
Intent intent =
new Intent(this, OtherActivity3.class);
startActivity(intent);
}
public void onClick4(View view) {
Intent intent =
new Intent(this, OtherActivity4.class);
startActivity(intent);
}
I think what seemed to happen then is the code wasnt confused or stuck in a loop (it didnt crash on my original posting). But instead now it goes straight to layout, gets the "onClick1" for button 1 and "onClick2" and matches them with the public void onClick(X) in MainActivity, because i have just declared i am using the ImageButton and an Intent, right after onClickListener, it works.
Note if i move around this code it breaks or will give me the same error. Regardless, i am happy it works but am intrigued as to why i did not have to declare all my buttons. Maybe it is just the logic in Java Code working.
I will definately try the switches and amendments later experimenting.
With best wishes.
in the MainActivity you should correctly implement OnClickListener interface:
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.imageButton1:
Intent intent =
new Intent(this, OtherActivity.class);
startActivity(intent);
break;
case R.id.imageButton2:
Intent intent =
new Intent(this, OtherActivity2.class);
startActivity(intent);
break;
}
}

How can I make multiple activities be in one activity changing only strings?

I have an app that contains a ListView in its menu which I want to link to one activity with the same layout style but the content inside should be different after being clicked on.
The ListView contains a list of songs, and the layout of an individual item when clicked contains a Title (TextView), Lyrics (TextView), a "next_button" button, a "previous_button" button to move between songs, a "back_button" button to get back to the ListView and a "play_tune" button which plays audio for that specific song. Not all of the songs contain audio, but where the "play_tune" button lies, I would like the app icon ic_launcher-web.png showing there instead.
The XML file I would like to show (for a song with audio) is shown below:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/song"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".ScoutSongs" >
<TextView
android:id="#+id/Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:textColor="#FFFFFF"
android:textSize="20sp" />
<ImageButton
android:id="#+id/play_tune"
android:src="#drawable/play_tune"
android:contentDescription="#string/play_tune"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/Title"
android:layout_alignTop="#+id/Title" />
<ScrollView
android:id="#+id/LyricsView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/back_button"
android:layout_alignLeft="#+id/Title"
android:layout_alignRight="#+id/play_tune"
android:layout_below="#+id/play_tune" >
<TextView
android:id="#+id/Lyrics"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFF" />
</ScrollView>
<Button
android:id="#+id/back_button"
android:layout_width="65dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/LyricsView"
android:text="#string/back"
android:textColor="#FFFFFF" />
<Button
android:id="#+id/previous_button"
android:layout_width="95dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/back_button"
android:layout_alignBottom="#+id/back_button"
android:layout_alignLeft="#+id/LyricsView"
android:text="#string/previous"
android:textColor="#FFFFFF" />
<Button
android:id="#+id/next_button"
android:layout_width="95dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/previous_button"
android:layout_alignBottom="#+id/previous_button"
android:layout_toRightOf="#+id/previous_button"
android:text="#string/next"
android:textColor="#FFFFFF" />
My current SongActivity.java file is shown below:
package com.lmarshall1995.scoutsongs;
import com.lmarshall1995.scoutsongs.R;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
public class SongActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.song);
Intent i = getIntent();
String Title = i.getStringExtra("Title");
String Lyrics = i.getStringExtra("Lyrics");
String TuneToast = i.getStringExtra("TuneToast");
String Tune = i.getStringExtra("Tune");
setupNavigationButton();
Toast toast = Toast.makeText(this, TuneToast , Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
final Button back = (Button) findViewById(R.id.back_button);
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
final Button previous = (Button) findViewById(R.id.previous_button);
previous.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent previousIntent = new Intent(SongActivity.this, SongActivity.class);
SongActivity.this.startActivity(previousIntent);
finish();
}
});
final Button next = (Button) findViewById(R.id.next_button);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent nextIntent = new Intent(SongActivity.this, SongActivity.class);
SongActivity.this.startActivity(nextIntent);
finish();
}
});
final ImageButton play_tune = (ImageButton) findViewById(R.id.play_tune);
play_tune.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ImageButton play_tune = (ImageButton) findViewById(R.id.play_tune);
play_tune.setOnClickListener(new View.OnClickListener() {
MediaPlayer mp = MediaPlayer.create(SongActivity.this, Tune);
public void onClick(View arg0) {
if (mp.isPlaying()) {
mp.stop();
mp.prepareAsync();
mp.seekTo(0);
} else {
mp.start();
}
}
});
}
});
}
private void setupNavigationButton() {}
}
And my Menu.java for my ListView is here:
package com.lmarshall1995.scoutsongs;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
public class Menu extends ListActivity{
String classes[] = {"Song_AliceTheCamel_Activity", "Song_Bingo_Activity",
"Song_CampfiresBurning_Activity", "Song_DownAtTheStation_Activity",
"Song_EverywhereWeGo_Activity", "Song_FeFi_Activity",
"Song_GingGangGooly_Activity", "Song_HeadShouldersKneesToes_Activity",
"Song_IfYoureHappyAndYouKnowIt_Activity", "Song_JoesButtonFactory_Activity",
"Song_Kumbaya_Activity", "Song_LittleGreenFrog_Activity",
"Song_Meatball_Activity", "Song_NationalAnthem_Activity",
"Song_OldMacDonald_Activity", "Song_PizzaHut_Activity",
"Song_QuartermastersStores_Activity", "Song_RowRowRowYourBoat_Activity",
"Song_ShineUpYourButtons_Activity", "Song_ThreeBlindJellyfish_Activity",
"Song_Underwear_Activity", "Song_Valerie_Activity", "Song_Worms_Activity",
"Song_XCommissionersInTheTown_Activity", "Song_YogiBear_Activity",
"Song_ZipADeeDooDah_Activity"};
String items[] = {"Alice The Camel", "Bingo", "Campfire\'s Burning", "Down At The Station",
"Everywhere We Go", "Fe Fi", "Ging Gang Gooly", "Head, Shoulders, Knees & Toes",
"If You\'re Happy And You Know It", "Joe\'s Button Factory", "Kumbaya",
"Little Green Frog", "Meatball", "National Anthem (UK)", "Old MacDonald", "Pizza Hut",
"Quartermaster\'s Stores", "Row, Row, Row Your Boat", "Shine Up Your Buttons",
"Three Blind Jellyfish", "Underwear", "Valerie", "Worms",
"X-Commissioner\'s In The Town", "Yogi Bear", "Zip A Dee Doo Dah"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
final ImageButton settings = (ImageButton) findViewById(R.id.settings_button);
settings.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent settingsIntent = new Intent(Menu.this, Settings.class);
Menu.this.startActivity(settingsIntent);
}
});
final ImageButton back = (ImageButton) findViewById(R.id.exit_button);
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
setListAdapter(new ArrayAdapter<String>(Menu.this, android.R.layout.simple_list_item_1, items));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(Menu.this, SongActivity.class);
i.putExtra("Title", "Song_" + classes + "_Title");
i.putExtra("Lyrics", "Song_" + classes + "_Lyrics");
i.putExtra("TuneToast", "To be sung in the tune of \n" + classes);
startActivity(i);
}
}
All of my Titles and Lyrics are currently in my Values\strings.xml file.
How can I make all my songs be in one "SongActivity" class after being selected in ListView? I believe that if you have to write anything out more than once, there should be an easier way to do it.
Edit: How can I make MediaPlayer mp = MediaPlayer.create(SongActivity.this, Tune); and String Tune = i.getStringExtra("Tune"); work together?
When selecting a list item, call your SongActivity with extras in the intent, such as SongName and other params you need. Then read it and populate the fields accordingly.
onItemSelected method:
Intent i = new Intent(this, SongActivity.class);
i.putExtra("songName", "Song name here"); //get song name from the item selected
....
startActivity(i);
In your SongActivity class:
onCreate(...){
Intent i = getIntent();
String songName = i.getStringExtra("songName");
...
}
Edit: this way all other fixed text can be included in SongActivity, just send the song to that activity
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String song = l.getItemAtPosition(position).toString(); //this is the selected song
Intent i = new Intent(Menu.this, SongActivity.class);
i.putExtra("Song", song);
startActivity(i);
}

Categories