I'm new in android development and I really can't figure out how to do that. So, I'm building an android app that stream music online via url. There is an url that shows current song. here is the url
I created a textView in my activity_main file to put current song text inside it, but I can't figure out how. I understand that I need to make variable url, then I need to parse that URL and put it inside text view. Or not?
Here is my MainActivity.java:
import androidx.appcompat.app.AppCompatActivity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button btn;
private TextView currentSong;
private boolean playPause;
private MediaPlayer mediaPlayer;
private boolean initialStage = true;
private ProgressBar pgsBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.audioStreamBtn);
currentSong = (TextView) findViewById(R.id.currentSong);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
pgsBar = findViewById(R.id.progressBar);
pgsBar.setVisibility(View.GONE);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!playPause) {
btn.setText("Stop");
if (initialStage) {
new Player().execute("stream url ...");
} else {
if (!mediaPlayer.isPlaying())
mediaPlayer.start();
}
playPause = true;
} else {
btn.setText("Play");
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
playPause = false;
}
}
});
}
class Player extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... strings) {
Boolean prepared = false;
try {
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
initialStage = true;
playPause = false;
btn.setText("Play");
mediaPlayer.stop();
mediaPlayer.reset();
}
});
mediaPlayer.prepare();
prepared = true;
} catch (Exception e) {
prepared = false;
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if (pgsBar.getVisibility() == View.VISIBLE) {
pgsBar.setVisibility(View.GONE);
btn.setEnabled(true);
}
mediaPlayer.start();
initialStage = true;
}
#Override
protected void onPreExecute() {
mediaPlayer.reset();
super.onPreExecute();
pgsBar.setVisibility(View.VISIBLE);
btn.setEnabled(false);
}
}
}
How do I pull out this text and put it in my textView "currentSong"?
You can use okHttp library to make a network request to URL and it will get back the response as string. Modify the response according to your liking and use that value for setText() of text view .
Use Retrofit or Volley to make a URL request.
possible duplicate of Make an HTTP request with android
Related
I'm new to Android and Java development. I'm trying to make an app that plays an Icecast audio stream.
I found, copied and edited the below code into a class called Audio Stream
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import java.io.IOException;
public class AudioStream extends Activity implements OnClickListener {
private Button buttonPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeUIElements();
initializeMediaPlayer();
Log.d("Classloaded", "Class loaded");
}
private void initializeUIElements() {
buttonPlay = findViewById(R.id.PlayPauseButton);
buttonPlay.setOnClickListener(this);
}
public void onClick(View v) {
Log.d("onClick", "On Click worked");
if (v == buttonPlay) {
startPlaying();
}
}
private void startPlaying() {
buttonPlay.setEnabled(false);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("streamURL");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Log.i("Buffering", "" + percent);
}
});
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
When I run the app the neither of the Log.d events fire off so I can only assume the class is never loaded and instanced. So I added the tried the following in MainActivity
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AudioStream stream = new AudioStream();
}
}
I know I'm doing something wrong. How do I get the AudioStream class to instance when the app loads so that the OnClickListener will work when I press the play button?
Instead of :
public void onClick(View v) {
Log.d("onClick", "On Click worked");
if (v == buttonPlay) {
startPlaying();
}
}
you should do like :
public void onClick(View v) {
Log.d("onClick", "On Click worked");
if (v.getId == R.id.PlayPauseButton) {
startPlaying();
}
}
First of all, I'm new to Java. Second, my intents here are as follows:
User clicks button (playPause) -> button toggles to pause drawable (pause1) and stream begins and user clicks button -> stream pauses and button toggles to play drawable(play1).
Now my problem is how to implement this behavior, an onClick method, inside of the current method playPauseMusic which contains an onPrepared method that is used to prepare the MediaPlayer asynchronously.
My intuition is to make a check for isPlaying and toggle from there, but my attempts so far have ended in failure.
Here is the relevant code and thank you for your time:
radio.java
package com.example.jacob.wutk;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import java.io.IOException;
public class radio extends AppCompatActivity {
/** Called when the user touches the button */
public void playMusic(View view) throws IOException {
String url = "http://streamer.cci.utk.edu:8000/wutk-vorbis"; // your URL here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mediaPlayer){
mediaPlayer.start();
}
});
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaPlayer.prepareAsync();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
}
}
I hope this helps.
public class radio extends AppCompatActivity {
MediaPlayer mediaPlayer;
boolean prepared=false;
public void playMusic(View view) throws IOException {
playpause();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
mediaPlayer = new MediaPlayer();
String url = "http://streamer.cci.utk.edu:8000/wutk-vorbis";
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mediaPlayer){
prepared=ture;
}
});
}
}
public void playPause() {
if (!mediaplayer.isPlaying()&&prepared) {
mediaplayer.start();
mediaplayer.setImageResource(R.drawable.ic_pause);
} else if(mediaplayer.isPlaying()) {
mediaplayer.pause();
mediaplayer.setImageResource(R.drawable.ic_play);
}
}
I tried a lot with my code below . there is no compile error at all. when I used to start the MP3 which I added , in the logcat window it shows "start called in state 0". please help me with this code . Thanks in advance .I also want to know when we pause the audio , i need to get the song resume from there when i click the start button (or) Is there any resume function for it , Let me know in the comments section . Thanks in advance. Here's my Java code
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mButton = (Button) findViewById(R.id.btnStart);
Button mButton1 = (Button) findViewById(R.id.btnStop);
Button mButton2 = (Button) findViewById(R.id.btnPause);
mp = new MediaPlayer();
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.start();
}
});
mButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
}
});
mButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer.create(MainActivity.this, R.raw.ch);
mp.pause();
}
});
create a class named AudioClip
public class AudioClip {
public static boolean loop = false;
public static MediaPlayer mediaPlayer;
private static SoundPool soundPool;
public static boolean isplayingAudio = false;
public static void playAudio(Context c, int id) {
mediaPlayer = MediaPlayer.create(c, id);
soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
if (!mediaPlayer.isPlaying()) {
isplayingAudio = true;
mediaPlayer.start();
mediaPlayer.setLooping(loop);
}
}
public static void stopAudio() {
isplayingAudio = false;
mediaPlayer.stop();
}
}
on other activity to play music
Context m = CuteActivity.this;
AudioClip.playAudio(m, R.raw.ch);\
and to stop
if (AudioClip.isplayingAudio) {
AudioClip.stopAudio();
}
I have no clue how to fix this, please help!
I am creating a counter app that shows numbers every time user press a button. It starts from 0 and to a maximum of 9999. My problem is that after the user closes the app it again starts from 0 but what I want is display the last number the user pressed instead of 0 when user open app again. I tried many shared preference codes but none of them worked. Here is my code:
import android.content.Context;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private int x;
Context context = this;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView number=(TextView) findViewById(R.id.numbers);
ImageButton btn_count=(ImageButton) findViewById(R.id.btn_countn);
ImageButton btn_reset=(ImageButton) findViewById(R.id.btn_resetn);
mp = MediaPlayer.create(context, R.raw.button_press);
number.setText(String.format("%04d", x)+"");
btn_count.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.button_press);
} mp.start();
} catch(Exception e) { e.printStackTrace(); }
x = x +1;
number.setText(String.format("%04d", x)+"");
}
});
btn_reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.button_press);
} mp.start();
} catch(Exception e) { e.printStackTrace(); }
x=0;
number.setText(String.format("%04d", x)+"");
}
});
}
}
You will need to use the Android Preferences for this:
How?
define when the app is getting closed and then call a method where you can write the actual value of the counter
Example
SharedPreferences buttonCounterValue = getSharedPreferences("counter", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = buttonCounterValue.edit();
editor.putInt("myCounter", i); //
editor.commit();
and when the app is open again you will need to call another method and read it back...
Example:
SharedPreferences buttonCounterValue = getPreferences(Activity.MODE_PRIVATE);
int storedCounter = buttonCounterValue.getInt("myCounter", 0);
so validate what you store and check if the preference you get is 0, that means nothing was stored before, so you can beging the game from 0...
Using SharedPreferences you can do something like this:
public class MainActivity extends AppCompatActivity {
private int x;
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
x = prefs.getInt("count", 0);
final TextView number=(TextView) findViewById(R.id.numbers);
ImageButton btn_count=(ImageButton) findViewById(R.id.btn_countn);
ImageButton btn_reset=(ImageButton) findViewById(R.id.btn_resetn);
number.setText(String.valueOf(x));
btn_count.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
x++;
prefs.edit().putInt("count", x).apply();
number.setText(String.valueOf(x));
}
});
btn_reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
x=0;
prefs.edit().putInt("count", x).apply();
number.setText(String.valueOf(x));
}
});
}
}
I am following the examples given in the Google tutorial to create a Google App Engine backend for my android app.
In the tutorial, the MainActivity is as follows:
import java.io.IOException;
import java.util.Date;
import android.os.AsyncTask;
import android.content.Context;
import com.cloudnotes.noteendpoint.Noteendpoint;
import com.cloudnotes.noteendpoint.model.Note;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.json.jackson.JacksonFactory;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new EndpointsTask().execute(getApplicationContext());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public class EndpointsTask extends AsyncTask<Context, Integer, Long> {
protected Long doInBackground(Context... contexts) {
Noteendpoint.Builder endpointBuilder = new Noteendpoint.Builder(
AndroidHttp.newCompatibleTransport(),
new JacksonFactory(),
new HttpRequestInitializer() {
public void initialize(HttpRequest httpRequest) { }
});
Noteendpoint endpoint = CloudEndpointUtils.updateBuilder(
endpointBuilder).build();
try {
Note note = new Note().setDescription("Note Description");
String noteID = new Date().toString();
note.setId(noteID);
note.setEmailAddress("E-Mail Address");
Note result = endpoint.insertNote(note).execute();
} catch (IOException e) {
e.printStackTrace();
}
return (long) 0;
}
}
}
This worsk fine and the entities are created everytime i run the app.So i modified it by adding textfields to get the values of description and email from the user and got this as the new MainActivity
public class MainActivity extends Activity implements View.OnClickListener{
EditText descriptionTF;
EditText emailTF;
Button submitBtn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
submitBtn = (Button) findViewById(R.id.submitButton);
descriptionTF = (EditText) findViewById(R.id.descriptionTextField);
emailTF = (EditText) findViewById(R.id.emailTextField);
}
public class EndpointsTask extends AsyncTask<Context, Integer, Long> {
protected Long doInBackground(Context... contexts) {
Noteendpoint.Builder endpointBuilder = new Noteendpoint.Builder(
AndroidHttp.newCompatibleTransport(),
new JacksonFactory(),
new HttpRequestInitializer() {
public void initialize(HttpRequest httpRequest) { }
});
Noteendpoint endpoint = CloudEndpointUtils.updateBuilder(
endpointBuilder).build();
String descrptn = descriptionTF.getText().toString();
String email = emailTF.getText().toString();
String noteID = new Date().toString();
try {
Note note = new Note();
note.setDescription(descrptn);
note.setId(noteID);
note.setEmailAddress(email);
Note result = endpoint.insertNote(note).execute();
} catch (IOException e) {
e.printStackTrace();
}
return (long) 0;
}
}
#Override
public void onClick(View v) {
if (v.getId()== R.id.submitButton) {
new EndpointsTask().execute(getApplicationContext());
}
}
}
Now nothing happens when i click the submit button.
I am guessing the problem is from me calling new EndpointsTask().execute(getApplicationContext()); from the onClick() method instead of the onCreate() method as it was done in the tutorial.Does anyone know a way around this?
Finally solved this problem by moving the onClick() method to the onCreate() method like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
submitBtn = (Button) findViewById(R.id.submitButton);
descriptionTF = (EditText) findViewById(R.id.descriptionTextField);
emailTF = (EditText) findViewById(R.id.emailTextField);
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId()== R.id.submitButton) {
new EndpointsTask().execute(getApplicationContext());
}
}
});
}