Android - How to create MediaPlayer from a user selected song - android

this is the intent which opens a chooser from the music app
public void launchMusicPlayer(View view) {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i,1);
}
and below is the onActivityResult code to try and obtain the song
, but the problem is that the test button when pressed, does not play anything
and as i am new to coding i don't know what i am doing wrong.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == 1) {
final MediaPlayer testSong = new MediaPlayer();
Uri songUri = data.getData();
try {
testSong.setDataSource(this, songUri);
} catch (IOException e) {
e.printStackTrace();
}
testSong.prepareAsync();
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
testSong.start();
}
});
}
}

The issue maybe because prepareAsync() is asynchronous, so the MediaPlayer may not be ready when you call start(). There are 2 ways to fix this:
Use prepare() instead of prepareAsync()
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
testSong.prepare();
testSong.start();
}
});
call start() method inside setOnPreparedListener()
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
testSong.prepareAsync();
testSong.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer player) {
player.start();
}
}
});
Refer to the documentation here http://developer.android.com/reference/android/media/MediaPlayer.html

Related

How to get Image different image URIs from different Images to ImageView on CropActivity?

Hey guys im new to programming in Android and i came to an issue, i have three ImageView and every time i click on these ImageViews i want it to start on CropActivity. Afterwards, if crop activity is done, it will retrieve its image Uri to the imageview i clicked. However the issue is whenever i click on ImageView 2, get the image,and then crop it, the image is set right away to the three of the ImageViews. And not on the Image View 2. I tried searching online and cant seem to find the answer to it.
Here is my onCreate
public class EditProfileActivity extends AppCompatActivity {
private CardView profileImageEdit, profileImageEdit2, profileImageEdit3;
ImageView ivBack, ImageUploaded1, ImageUploaded2, ImageUploaded3;
Uri imageUri1, imageUri2, imageUri3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
profileImageEdit = findViewById(R.id.profileImageEdit);
profileImageEdit2 = findViewById(R.id.profileImageEdit2);
profileImageEdit3 = findViewById(R.id.profileImageEdit3);
ImageUploaded1 = findViewById(R.id.ImageUploaded1);
ImageUploaded2 = findViewById(R.id.ImageUploaded2);
ImageUploaded3 = findViewById(R.id.ImageUploaded3);
profileImageEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CropImage.activity()
.setAspectRatio(1, 1)
.start(EditProfileActivity.this);
}
});
profileImageEdit2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CropImage.activity()
.setAspectRatio(1, 1)
.start(EditProfileActivity.this);
}
});
profileImageEdit3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CropImage.activity()
.setAspectRatio(1, 1)
.start(EditProfileActivity.this);
}
});
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(EditProfileActivity.this, ProfileActivity.class));
}
});
below the above Line is my cropActvity onActivity result
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
imageUri1 = result.getUri();
imageUri2 = result.getUri();
imageUri3 = result.getUri();//this is the problem
ImageUploaded1.setImageURI(imageUri1);
ImageUploaded2.setImageURI(imageUri2);
ImageUploaded3.setImageURI(imageUri3);
} else {
startActivity(new Intent(EditProfileActivity.this, ProfileActivity.class));
finish();
}
}
Here is the image: EditProfile
Many thanks guys!
create new imageView instance:
ImageView pickedImageView;
after every profileImageEdit set it to clicked ImageView:
ImageView pickedImageView;
profileImageEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CropImage.activity()
.setAspectRatio(1, 1)
.start(EditProfileActivity.this);
pickedImageView = profileImageEdit;
}
});
profileImageEdit2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CropImage.activity()
.setAspectRatio(1, 1)
.start(EditProfileActivity.this);
pickedImageView = profileImageEdit2;
}
});
profileImageEdit3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CropImage.activity()
.setAspectRatio(1, 1)
.start(EditProfileActivity.this);
pickedImageView = profileImageEdit3;
}
});
modify your onActivityResult with following:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (pickedImageView != null)
pickedImageView.setImageURI(result.getUri());
} else {
startActivity(new Intent(EditProfileActivity.this, ProfileActivity.class));
finish();
}
}

Having trouble playing audio on the MediaPlayer in Android

New to Android coding here. I'm trying to have the user pick an audio file for the MediaPlayer to play using the "upload" button, and then the MediaPlayer should start playing the file once the user hits "play." Here is my code so far:
public class MainActivity extends Activity {
final int ACTIVITY_CHOOSE_FILE = 1;
File original;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) this.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent chooseFile;
Intent intent;
chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("audio/mpeg");
intent = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);
}
});
Button playButton = (Button)findViewById(R.id.playbutton);
playButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(original.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTIVITY_CHOOSE_FILE: {
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
original = new File(uri.getPath());
String tag = "TAG";
Log.d(tag, original.getAbsolutePath());
}
}
}
}
}
I can choose the audio file fine, but once I hit play nothing happens. What am I doing wrong?
After setting your mediaPlayer data source you have to call mediaPlayer.prepareAsync()
Media Playback in android

Media Player Crashing

I am new to programming and upon referring google's dev site I came up with a simple media player that plays the file selected by the user. The app seems to been running fine when choosing the file to be played for the first time but crashes right after selecting a file for the second time. I have pasted the code below. Any help will be appreciated.
public class MainActivity extends Activity {
private static int Reqs =1;
private String a;
MediaPlayer md=new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button Start = (Button) findViewById(R.id.button);
final Button Stop = (Button) findViewById(R.id.button3);
final Button Pause = (Button) findViewById(R.id.button2);
final Button Select = (Button) findViewById(R.id.button4);
Pause.setEnabled(false);
Stop.setEnabled(false);
Start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
md.start();
Toast.makeText(getApplicationContext(), "Playing", Toast.LENGTH_SHORT).show();
Pause.setEnabled(true);
Stop.setEnabled(true);
}
});
Stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Pause.setEnabled(false);
Toast.makeText(getApplicationContext(), "Stopped", Toast.LENGTH_SHORT).show();
md.stop();
}
});
Pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
md.pause();
Toast.makeText(getApplicationContext(), "Paused", Toast.LENGTH_SHORT).show();
}
});
Select.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("audio/mpeg");
startActivityForResult(Intent.createChooser(intent, "Choose"), Reqs);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode <= Reqs && resultCode ==-1) {
Uri videoUri = data.getData();
a = videoUri.toString();
md.setDataSource(a); //try-catch surrounding it
md.prepare(); //try-catch surrounding it
}
}
}
You are not calling reset() to reset the state of the MediaPlayer object.
As the Android's documentation states:
In order to reuse a MediaPlayer object that is in the Error state and recover from the error, reset() can be called to restore the object to its Idle state.
Check it at: https://developer.android.com/reference/android/media/MediaPlayer.html

Android code to add and view data through application

I am developing a Task manager( a simple one) to learn android and this is my short description.
I am making two activities one to view task and other to add ( and I am using an Application class through which i add the task)..
when i add the task on the addtask activity my viewtask activity still remains blank. Could you help me out.
This is my viewTask activity.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_task);
setupviews();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
System.out.println(requestCode);
if (requestCode == 1) {
showtask(); // your "refresh" code
}
}
public void OnResume()
{
super.onResume();
System.out.println("Its working...");
showtask();
}
/*public void onPause(){
super.onPause();
}*/
public void showtask()
{
ArrayList<Task> task=gettma().gettask();
StringBuffer sb=new StringBuffer();
for(Task t:task){
sb.append(String.format("* %s\n", t.toString()));
System.out.println("Its working...again");
}
taskText.setText(sb.toString());
}
private TaskManagerApplication gettma() {
TaskManagerApplication tma1=(TaskManagerApplication)getApplication();
return tma1;
}
private void setupviews() {
AddButton=(Button)findViewById(R.id.AddButton);
taskText=(TextView)findViewById(R.id.TextList);
AddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(ViewTask.this,AddTask.class);
startActivity(intent);
}
});
}
}
And this is my Addtask activity.
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.addtask);
setupviews();
}
protected void addtask() {
String name=EditText.getText().toString();
Task t= new Task(name);
//System.out.println("its working here");
gettma().addTask(t);
finish();
}
private TaskManagerApplication gettma() {
TaskManagerApplication tma=(TaskManagerApplication)getApplication();
return tma;
}
private void setupviews() {
EditText=(EditText)findViewById(R.id.EditText);
AddButton=(Button)findViewById(R.id.AddButton1);
CancelButton=(Button)findViewById(R.id.CancelButton);
AddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addtask();
}
});
CancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
}
Please Help
EditText=(EditText)findViewById(R.id.EditText);
This is the line in your setupviews(). You cannot do this because EditText is a class and you need a variable of that type to which you can assign a value. It must be EditText followed by some variable name.
if (requestCode == 1) {
showtask(); // your "refresh" code
}
This is in your onActivityResult(). You aren't checking the resultCode to check if the called Activity failed to do the operation that would produce a result.
Also, in numerous places you arent following the Java naming convention. Please, use upper and lower cases properly when naming variables and classes.

can't call onactivity result function after child activity is finished

i am using following codes.
addNewReceipt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(v.getContext(), AddReceipt.class);
myIntent.putExtra("receiptList", receipts);
startActivityForResult(myIntent, RECEIPT_ADD);
}
});
}
#SuppressWarnings("unchecked")
public synchronized void onActivityResult(final int requestCode, int resultCode, final Intent data)
{
if (resultCode == Activity.RESULT_OK)
{
if (requestCode == RECEIPT_ADD)
{
receipts = (ArrayList<Receipt>) data.getSerializableExtra("receiptList");
addReceiptsInListView();
}
}
}
The code for AddReceipt class is as follow,
#Override
public void finish() {
Intent data = new Intent();
data.putExtra("receiptList", receipts);
setResult(RESULT_OK, data);
super.finish();
}
#SuppressWarnings("unchecked")
public void onCreateCall()
{
done.setOnClickListener(new OnClickListener()
{ //receiptAddBtn
#Override
public void onClick(View v)
{
String error = "";
Receipt receipt = new Receipt();
receipt.comments = comments.getText().toString();
receipt.referenceNo = receiptNo.getText().toString();
receipt.image = imageSelected;
if (receipt.image == null || receipt.referenceNo == "" )
{
error = "Please input Receipt No. and attach Image";
displayAlert(error);
}
else
{
receipts.add(receiptCounter,receipt);
finish();
}
}
});
}
The problem is, when the activity is finished... and i pass this receipt, in my previous class from which i call this activity public synchronized void onActivityResult Never works.
The back button is not ending activity either.
Please tell me where i am wrong,.
Best Regards
Here is the solution to your problem
#Override
public void finish() {
Intent data = new Intent();
data.putExtra("receiptList", receipts);
setResult(Activity.RESULT_OK, data);
super.finish();
}

Categories

Resources