I am using this code to swipe between layouts and I would like it to open audio files.
I try to work it so: I swiped from first to second layout, and when layout second came, it should open an audio file.
I tried to use "switch", but I don't know how to properly implement it.
Thanks!
I have done this!
Just add OnPageChangeListener to code.
So it will look like:
mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int page) {
// TODO Auto-generated method stub
switch (mViewPager.getCurrentItem()) {
case 0: //first layout
audio1.start();
break;
case 1: //second layout
audio2.start();
break;
//other case, other layouts
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
In my opinion, you should declare a MediaPlayer object within your switch block, give it an Uri containing your audio file path and play your file.
public void moveTo(View v) {
// switch the ViewPager according to the button clicked
int page = 0;
Uri songUri = Uri.parse("musicPath");
player = MediaPlayer.create(context, songUri);
player.start();
switch (v.getId()) {
[...]
I do not know if your music file is like just a few seconds long sound or a whole music track but if it is the first case, it is the best way.
Related
I am new to the fragment.
in Activity, I have two onClick methods which are:
click that override the method
normal onclick
how can I change the onclick that override the method to fragment?
private void searchMobileNumber() {
mRecyclerView.addOnItemTouchListener(new SelectExistingOrNewNoFragment.RecyclerTouchListener(PostpaidRegistrationActivity.this, mRecyclerView, new SelectExistingOrNewNoFragment.ClickListener() {
#Override
public void onClick(View view, int position) {
selectedPostion = position;
mob_number_detail_lyt.setVisibility(View.GONE);
mobile_no_head_lyt.setVisibility(View.VISIBLE);
mobile_number_success.setImageDrawable(getResources().getDrawable(R.drawable.validation_correct));
if (simCardFirstTime) {
simCardFirstTime = false;
final Intent intent = new Intent(PostpaidRegistrationActivity.this, MyScanActivity.class);
intent.putExtra("ocrType", "Barcode");
intent.putExtra("message", "Please scan your SIM card");
startActivityForResult(intent, MposConstants.SIMCARD_FIRST_TIME);
}
}
}
If I get this clear, you have two buttons. One of which is to start a fragment or do something with it.. You just need a switch case. Also, use the R class for the cases.
Use view.getId()
Code:
#Override
public void onClick(View view, int position) {
switch(view.getId()){
case R.id.fragment_button:
// do something with fragment
break;
default: break;
}
}
OK my question is a lot bigger than the Title. But can't describe everything in a Title. So here we go.
I am writing an App that when a NFC cards get detected by Phone, it will be able to WRITE and READ a NDEF message on / from it.
I use two buttons READ and WRITE to trigger these events. Everything works fine, just the thing that EVERYTHING REPEATS ITSELF FOUR (4x) TIMES!
Only the TAG "UltraLightCard Detected" and "Connected" pops once.
Everything else that you see in code in "ShowMessage" will pop out 4x times also the AlertDialog box gets triggered 4x times and you have to write the text 4 times.
If you wrote it only once and then clicked "Save" 3x times just to close it, it wont store the string.
Here's my code:
protected void ultralightCardLogic() {
final Button b_write = (Button)findViewById(R.id.b_write);
final Button b_read = (Button)findViewById(R.id.b_read);
b_write.setId(1);
b_read.setId(2);
//showImageSnap(R.drawable.ultralight);
ShowMessage("UltraLight Card Detected :" + mifareUL.getTagName(), 'a');
try {
mifareUL.connect();
mifareUL.formatT2T();
ShowMessage("Connected!" , 'd');
b_write.setOnTouchListener(new MyTouchListener());
b_read.setOnTouchListener(new MyTouchListener());
} catch (IOException e) {
e.printStackTrace();
}
}
Here is MyTouchListener:
public class MyTouchListener implements OnTouchListener{
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stu
int id = v.getId();
switch(id){
case 1:
onCreateDialog();
break;
case 2:
readNDEFmsg();
break;
case 3:
break;
}
return false;
}
}
Here is the OnCreateDialog:
final View v = getLayoutInflater().inflate(R.layout.dia_box,null);
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setView(v)
.setPositiveButton("SAVE", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int id) {
// TODO Auto-generated method stub
final EditText mEdit=(EditText)v.findViewById(R.id.et_dia);
String str = mEdit.getText().toString();
writeNDEFmsg(str);
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
If you guys need some more of the code, I can add it then. Don't want to write too much code, because my experience tells me that then noone will try to help me out.
Please, help me out
Thanks to your help I figured out my issue.
I used onTouchListener, which triggers more than once, since it has more MotionEvents available.
After I changed on to OnClickListener everything works smoothly!
Just be sure to implement View.OnClickListener
if you are doing it like I do in my public class MyClickListener.
Then Eclipse will auto-generate your necessary code. Extract the id of your buttons and do the switch statement (again, if you`re doing it this way):
public class MyClickListener implements android.view.View.OnClickListener{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int id = v.getId();
switch(id){
case 1:
onCreateDialog();
break;
case 2:
readNDEFmsg();
break;
case 3:
break;
}
}
Thanks again for the help! Hope it will help someone else too.
I am developing an android application and I want close the window of view adds after I click on the adds window using Resume event.I put a rule in resume event but this rule make adds never show. so if there is a way to make the view adds disappears when I return to my application?
this is my code:
#Override
protected void onResume() {
// TODO Auto-generated method stub
if (adView != null) {
adView.destroy();
}
super.onResume();
}
this is the right code:
protected void onResume() {
// TODO Auto-generated method stub
adView.setAdListener(new AdListener() {
#Override
public void onAdOpened() {
// Save app state before going to the ad overlay.
}
#Override
public void onAdClosed() {
adView.setVisibility(View.GONE);
// TODO Auto-generated method stub
super.onAdClosed();
}
});
super.onResume();
}
use following to disappear the view.
adView.setVisibility(View.GONE):
set an onClickListener on adView then in onClick call this method.
How can I write command in onclicklistener() so that I can move to next activity as well as my post status dialog will appear on that new activity. I am using intent for switching to next activity and also using postTowall() method. But these two doesn't perform simultaneously. I am using this method:
public void onClick(View v) {
// TODO Auto-generated method stub
postTowall();
Intent intent= new Intent(Frnd.this,Logout.class);
startActivity(intent);
}
private void postTowall() {
facebook.dialog(this, "feed", new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
public void onComplete(Bundle values) {
String sh = null;
Bundle params = new Bundle();
params.putString("caption", sh);
}
public void onCancel() {
// TODO Auto-generated method stub
}
You can use thread for posting. Use asynctask and inside that post the message to face book. Or you may just write a simple thread and start it.
This asynctask link may help you. it has usage example also:
http://developer.android.com/reference/android/os/AsyncTask.html
You should set other activity to open post dialog. Send via intent a signal if it should or not...
I'm currently working on my third Android project for mass release. My first two were relatively basic compared to my current application, which is by far my most complex work. As such, I've been having to deal with more listeners then I'm used to.
Specifically, the portion of my application with deals with playing a web stream in MediaPlayer is already using three listeners.
A listener for a spinner:
stationSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
String newStreamUrl;
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
switch (position) {
// Based on the user's selection, change the URL to match the appropriate station and stream quality.
case 0:
// 128kb 89.7 stream
// Default case, always executed on activity creation.
newStreamUrl = "defaultStreamUrl";
changeStream(newStreamUrl);
break;
case 1:
// 320kb stream
newStreamUrl = "URL1";
changeStream(newStreamUrl);
break;
case 2:
// 128kb Stream 2
newStreamUrl = "URL2";
changeStream(newStreamUrl);
break;
case 3:
// 320kb Steam 2
newStreamUrl = "URL3";
changeStream(newStreamUrl);
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
A listener for a progressDialog:
pd = ProgressDialog.show(this, "Loading...", "Buffering Stream", true, true, new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
pd.dismiss();
mp.reset();
}
});
And a listener to trigger playback when buffering is complete:
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// When the stream is buffered, kill prompt and start playing automatically.
pd.dismiss();
mp.start();
Log.i(TAG, "Stream playback started.");
}
});
...and I'm not even halfway finished with implementing listeners to deal with all possible situations.
From my current knowledge, a listener has to either be defined anonymously (as I have done above), or written as a separate class which implements the listener and then instantiated in the desired class. Maybe it's just me, but I think defining these anonymously clutters my code and obscures the logic behind the activity. However, since I'm really only using these listeners in this class, it seems like a waste to move them to their own separate file, as it will eat away the namespace of my package.
I'm wondering what the best practice is for a situation like this. Is there a well defined rule regarding listeners or is it just up to the preference of the developer? I'm trying to conform this project as close to best coding practices as I can, since I'm new to writing Android applications, so hopefully I can learn something from this. Any thoughts?
My entire code for context if necessary:
public class StreamActivity extends Activity {
static private MediaPlayer mp;
static ProgressDialog pd;
static String streamUrl = "defaultStreamURL"; // Default value is 128kb/s stream.
private static final String TAG = StreamActivity.class.getName(); // Tag constant for logging purposes
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.stream, menu);
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stream_layout);
// Build selection spinner
Spinner stationSpinner = (Spinner)findViewById(R.id.station_spinner);
ArrayAdapter<CharSequence> stationAdapter = ArrayAdapter.createFromResource(this, R.array.station_string_array, android.R.layout.simple_spinner_item);
stationAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
stationSpinner.setAdapter(stationAdapter);
// Set spinner decision logic
stationSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
String newStreamUrl;
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
switch (position) {
// Based on the user's selection, change the URL to match the appropriate station and stream quality.
case 0:
// 128kb 89.7 stream
// Default case, always executed on activity creation.
newStreamUrl = "defaultStreamUrl";
changeStream(newStreamUrl);
break;
case 1:
// 320kb stream
newStreamUrl = "URL1";
changeStream(newStreamUrl);
break;
case 2:
// 128kb Stream 2
newStreamUrl = "URL2";
changeStream(newStreamUrl);
break;
case 3:
// 320kb Steam 2
newStreamUrl = "URL3";
changeStream(newStreamUrl);
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
// Build audio player using default settings.
mp = buildAudioPlayer();
}
/**
* Builds and returns a configured, unprepared MediaPlayer.
*/
public MediaPlayer buildAudioPlayer() {
// Build MediaPlayer
mp = new MediaPlayer();
try {
mp.reset();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(streamUrl);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Caught IllegalArgumentException: ");
e.printStackTrace();
} catch (IllegalStateException e) {
Log.e(TAG, "Caught IllegalStateException: ");
e.printStackTrace();
} catch (SecurityException e) {
Log.e(TAG, "Caught SecurityException: ");
e.printStackTrace();
} catch (IOException e) {
Log.e(TAG, "Caught IOException: ");
e.printStackTrace();
}
pd = new ProgressDialog(this);
return mp;
}
protected void changeStream(String newStreamUrl) {
streamUrl = newStreamUrl;
// Stop stream if it is currently playing to prevent state exceptions
if (mp.isPlaying()) {
Log.i(TAG, "Stream source changed by user. Rebuilding stream.");
Log.i(TAG, "Stream playback stopped.");
mp.stop();
}
// Rebuild player with new stream URL.
mp.reset();
mp = buildAudioPlayer();
}
/**
* Stops audio, drops connection to stream, and returns Media Player to an unprepared state. Called by a button onClick event.
* #param v Button pressed by user.
*/
public void stopAudio(View v) {
mp.stop();
Log.i(TAG, "Stream playback stopped.");
}
/**
* Pauses audio with no change to connection or Media Player. Called by a button onClick event.
* #param v Button pressed by user.
*/
public void pauseAudio(View v) {
mp.pause();
Log.i(TAG, "Stream playback paused.");
}
/**
* Prepares Media Player asynchronously. Displays prompt while buffering and automatically starts when finished.
* #param v Button pressed by user.
*/
public void playAudio(View v) {
// If we are paused, resume playback without rebuffering.
if (mp.isPlaying()) {
mp.start();
} else {
// If audio is NOT playing, we need to prepare and buffer.
try {
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// When the stream is buffered, kill prompt and start playing automatically.
pd.dismiss();
mp.start();
Log.i(TAG, "Stream playback started.");
}
});
// Prepares stream without blocking UI Thread
mp.prepareAsync();
} catch (IllegalStateException e) {
Log.e(TAG, "Caught IllegalStateException when preparing: ");
e.printStackTrace();
}
// Stop user input while buffering by displaying ProgressDialog
pd.setCancelable(true);
pd.setCanceledOnTouchOutside(false);
pd = ProgressDialog.show(this, "Loading!", "Buffering...", true, true, new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
pd.dismiss();
mp.reset();
}
});
}
}
}
It clutters your code because you're making them too long. Reduce them to two or three lines max, and it will be more readable. For example:
stationSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView,
View selectedItemView,
int position,
long id) {
changeUrl(position);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
};
...
private void changeUrl(int spinnerPosition) {
String newStreamUrl;
switch (position) {
case 0:
// 128kb 89.7 stream
// Default case, always executed on activity creation.
newStreamUrl = "defaultStreamUrl";
changeStream(newStreamUrl);
break;
case 1:
// 320kb stream
newStreamUrl = "URL1";
changeStream(newStreamUrl);
break;
case 2:
// 128kb Stream 2
newStreamUrl = "URL2";
changeStream(newStreamUrl);
break;
case 3:
// 320kb Steam 2
newStreamUrl = "URL3";
changeStream(newStreamUrl);
}
}
}
Or, if it's still too long, you can implement them as non-anonymous inner classes. For example:
stationSpinner.setOnItemSelectedListener(new StationSpinnerListener());
...
private class StationSpinnerListener implements OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parentView,
View selectedItemView,
int position,
long id) {
String newStreamUrl;
switch (position) {
case 0:
// 128kb 89.7 stream
// Default case, always executed on activity creation.
newStreamUrl = "defaultStreamUrl";
changeStream(newStreamUrl);
break;
case 1:
// 320kb stream
newStreamUrl = "URL1";
changeStream(newStreamUrl);
break;
case 2:
// 128kb Stream 2
newStreamUrl = "URL2";
changeStream(newStreamUrl);
break;
case 3:
// 320kb Steam 2
newStreamUrl = "URL3";
changeStream(newStreamUrl);
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
}