I have chat app where user can share audio files. In recyclerview adapter i need to change icon of play button in following case:
Normally click on single item play button change into pause then into play again by clicking and on complete (Working fine)
Playing second audio file in recyclerview. Playing/Pause working ok but onComplete not calling on second audio file.
Playing other audio file while first audio file is playing. It should turn current position play button icon into pause and last position play button into pause.- Not working
I tried to save last position at onClick and used setTag/getTag etc. But i am not able to change icon of my play/pause button on MediaPlayer states.
My Recyclerview Adapter Code:
public class ChatAdapter extends PagingDataAdapter<TbsData, RecyclerView.ViewHolder> {
//0 stop , 1 play, 2 pause, 3 released
private static int MediaPlayer_State = 0;
MediaPlayer mPlayer= new MediaPlayer();
int mediaPlayerPlayingPosition = -1;
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.new_chat_audio, parent, false);
return new ViewHolderAudio(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int pos) {
customItem wrapper = getItem(holder.getAbsoluteAdapterPosition());
ViewHolderAudio ViewHolderAudio = (ViewHolderAudio) holder;
if(ViewHolderAudio.voicePlaybutton.getTag == null){
ViewHolderAudio.voicePlaybutton.setTag("playButton");
}
if (mPlayer==null){
mPlayer = new MediaPlayer();
}
ViewHolderAudio.audioSeekbar.setProgress(0);
if (ViewHolderAudio.voicePlaybutton.getTag().equals("playButton")){
Glide.with(context)
.load(R.drawable.ic_play_circle_outline_24px)
.into(ViewHolderAudio.voicePlaybutton);
}else {
Glide.with(context)
.load(R.drawable.ic_pause_circle_outline_24px)
.into(ViewHolderAudio.voicePlaybutton);
}
ViewHolderAudio.voicePlaybutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayerPlayingPosition == -1){
mediaPlayerPlayingPosition = ViewHolderAudio.getAbsoluteAdapterPosition();
}
if (mPlayer.isPlaying()) {
Glide.with(context)
.load(R.drawable.ic_play_circle_outline_24px)
.into(ViewHolderAudio.voicePlaybutton);
mPlayer.pause();
mPlayer.reset();
} else {
if (MediaPlayer_State == 2) {
MediaPlayer_State = 1;
mPlayer.start();
ViewHolderAudio.visualizer.setPlayer(mPlayer.getAudioSessionId());
ViewHolderAudio.audioSeekbar.setMax(mPlayer.getDuration());
} else {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
mPlayer.setDataSource(context, Uri.parse(wrapper.getUSER_MESSAGE()));
} else {
mPlayer.setDataSource(wrapper.getUSER_MESSAGE());
}
mPlayer.prepare();
mPlayer.start();
MediaPlayer_State = 1;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, "Unable to play audio", Toast.LENGTH_SHORT).show();
}
}
Glide.with(context)
.load(R.drawable.ic_pause_circle_outline_24px)
.into(ViewHolderAudio.voicePlaybutton);
}
}
});
mpOncomplete(mPlayer,ViewHolderAudio.voicePlaybutton,ViewHolderAudio.audioSeekbar);
/*mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
Log.d(TAG, "onCompletion: "+context);
ViewHolderAudio.audioSeekbar.setProgress(0);
mPlayer.reset();
Glide.with(context)
.load(R.drawable.ic_play_circle_outline_24px)
.into(ViewHolderAudio.voicePlaybutton);
MediaPlayer_State = 0;
}
});*/
mediaMetadataRetrieverVoice.release();
pausePlayer = new MediaPlayerPause() {
#Override
public void pausePlayer(int state) {
Log.d(TAG, "pausePlayer: Pause Media Player Interface "+state);
if (state == 2 && mPlayer.isPlaying()) {
mPlayer.pause();
MediaPlayer_State = 2;
} else if (state == 3) {
mPlayer.release();
mPlayer = null;
MediaPlayer_State = 3;
}
Glide.with(context)
.load(R.drawable.ic_play_circle_outline_24px)
.into(ViewHolderAudio.voicePlaybutton);
}
};
}
public class ViewHolderAudio extends RecyclerView.ViewHolder {
ImageView audioThumnail, voicePlaybutton;
TextView audioDuration, audioTimestamp,voiceTitle;
SeekBar audioSeekbar;
ImageView msgDeliveryStatus;
public ViewHolderAudio(#NonNull View itemView) {
super(itemView);
userImage = itemView.findViewById(R.id.userImage);
audioThumnail = itemView.findViewById(R.id.audioThumbImage);
voiceTitle = itemView.findViewById(R.id.voiceTitle);
voicePlaybutton = itemView.findViewById(R.id.voicePlayButton);
audioSeekbar = itemView.findViewById(R.id.seekBar);
}
}
private void mpOncomplete (final MediaPlayer mp,ImageView view,SeekBar bar){
Log.d(TAG, "mpOncomplete: Media Player ");
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
bar.setProgress(0);
mediaPlayer.stop();
mediaPlayer.reset();
Glide.with(context)
.load(R.drawable.ic_play_circle_outline_24px)
.error(R.drawable.ic_image_not_found).into(view);
MediaPlayer_State = 0;
}
});
}
private void changeIcon(int mediaPlayerPlayingPosition, ImageView voicePlaybutton) {
notifyItemChanged(mediaPlayerPlayingPosition);
}
}
Related
Below is my code snippets.
1) CustomAdapter
public class CustomAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
// A menu item view type.
private static final int MENU_ITEM_VIEW_TYPE = 0;
// The unified native ad view type.
private static final int UNIFIED_NATIVE_AD_VIEW_TYPE = 1;
ListActivity listActivity;
List<Object> mModelList;
public CustomAdapter(ListActivity listActivity, List<Object> modelList) {
this.listActivity = listActivity;
this.mModelList = modelList;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case UNIFIED_NATIVE_AD_VIEW_TYPE:
View unifiedNativeLayoutView = LayoutInflater.from(
parent.getContext()).inflate(R.layout.ad_unified,
parent, false);
return new UnifiedNativeAdViewHolder(unifiedNativeLayoutView);
case MENU_ITEM_VIEW_TYPE:
// Fall through.
default:
//inflate layout
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.model_layout, parent, false);
MenuItemViewHolder holder = new MenuItemViewHolder(itemView);
//Handle item clicks here
holder.setOnClickListener(new MenuItemViewHolder.ClickListener() {
#Override
public void onItemClick(View view, int position) {
Model modelList = (Model) mModelList.get(position);
//This is called when user clicks item
String id = modelList.getId();
String title = modelList.getTitle();
String description = modelList.getDescription();
Long time = modelList.getTime();
//intent to start activity
Intent intent = new Intent(listActivity, PostDetails.class);
//put data in intent
intent.putExtra("pId", id);
intent.putExtra("pTitle", title);
intent.putExtra("pDescription", description);
intent.putExtra("pTime", time);
//start activity
listActivity.startActivity(intent);
}
#Override
public void onItemLongClick(View view, int position) {
}
});
return holder;
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
int viewType = getItemViewType(position);
switch (viewType){
case UNIFIED_NATIVE_AD_VIEW_TYPE:
UnifiedNativeAd nativeAd = (UnifiedNativeAd) mModelList.get(position);
populateNativeAdView(nativeAd, ((UnifiedNativeAdViewHolder) holder).getAdView());
break;
default:
// fall through
case MENU_ITEM_VIEW_TYPE:
MenuItemViewHolder menuItemHolder = (MenuItemViewHolder) holder;
Model modelList = (Model) mModelList.get(position);
//bind views / set data
menuItemHolder.mTitleTv.setText(modelList.getTitle());
menuItemHolder.mDescriptionTv.setText(modelList.getDescription());
menuItemHolder.setTime(modelList.getTime());
}
}
#Override
public int getItemCount() {
return mModelList.size();
}
#Override
public int getItemViewType(int position) {
Object recyclerViewItem = mModelList.get(position);
if (recyclerViewItem instanceof UnifiedNativeAd) {
return UNIFIED_NATIVE_AD_VIEW_TYPE;
}
return MENU_ITEM_VIEW_TYPE;
}
private void populateNativeAdView(UnifiedNativeAd nativeAd,
UnifiedNativeAdView adView) {
// Some assets are guaranteed to be in every UnifiedNativeAd.
((TextView) adView.getHeadlineView()).setText(nativeAd.getHeadline());
((TextView) adView.getBodyView()).setText(nativeAd.getBody());
((Button) adView.getCallToActionView()).setText(nativeAd.getCallToAction());
// These assets aren't guaranteed to be in every UnifiedNativeAd, so it's important to
// check before trying to display them.
NativeAd.Image icon = nativeAd.getIcon();
if (icon == null) {
adView.getIconView().setVisibility(View.INVISIBLE);
} else {
((ImageView) adView.getIconView()).setImageDrawable(icon.getDrawable());
adView.getIconView().setVisibility(View.VISIBLE);
}
if (nativeAd.getPrice() == null) {
adView.getPriceView().setVisibility(View.INVISIBLE);
} else {
adView.getPriceView().setVisibility(View.VISIBLE);
((TextView) adView.getPriceView()).setText(nativeAd.getPrice());
}
if (nativeAd.getStore() == null) {
adView.getStoreView().setVisibility(View.INVISIBLE);
} else {
adView.getStoreView().setVisibility(View.VISIBLE);
((TextView) adView.getStoreView()).setText(nativeAd.getStore());
}
if (nativeAd.getStarRating() == null) {
adView.getStarRatingView().setVisibility(View.INVISIBLE);
} else {
((RatingBar) adView.getStarRatingView())
.setRating(nativeAd.getStarRating().floatValue());
adView.getStarRatingView().setVisibility(View.VISIBLE);
}
if (nativeAd.getAdvertiser() == null) {
adView.getAdvertiserView().setVisibility(View.INVISIBLE);
} else {
((TextView) adView.getAdvertiserView()).setText(nativeAd.getAdvertiser());
adView.getAdvertiserView().setVisibility(View.VISIBLE);
}
// Assign native ad object to the native view.
adView.setNativeAd(nativeAd);
}
}
2) MenuItemViewHolder class
public class MenuItemViewHolder extends RecyclerView.ViewHolder {
TextView mTitleTv, mDescriptionTv, mPostTimeTv;
View mView;
public MenuItemViewHolder(#NonNull View itemView) {
super(itemView);
mView = itemView;
//item click
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mClickListener.onItemClick(v, getAdapterPosition());
}
});
//iten long Click Listener
itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
mClickListener.onItemLongClick(v, getAdapterPosition());
return true;
}
});
//set time
//initialize views with model_layout.xml
mTitleTv = itemView.findViewById(R.id.rTitleTv);
mDescriptionTv = itemView.findViewById(R.id.rDescriptionTv);
mPostTimeTv = itemView.findViewById(R.id.postTime);
}
public void setTime(Long time) {
TextView txtTime = (TextView) mView.findViewById(R.id.postTime);
//long elapsedDays=0,elapsedWeeks = 0, elapsedHours=0,elapsedMin=0;
long elapsedTime;
long currentTime = System.currentTimeMillis();
int elapsed = (int) ((currentTime - time) / 1000);
if (elapsed < 60) {
if (elapsed < 2) {
txtTime.setText("Just Now");
} else {
txtTime.setText(elapsed + " sec ago");
}
} else if (elapsed > 604799) {
elapsedTime = elapsed / 604800;
if (elapsedTime == 1) {
txtTime.setText(elapsedTime + " week ago");
} else {
txtTime.setText(elapsedTime + " weeks ago");
}
} else if (elapsed > 86399) {
elapsedTime = elapsed / 86400;
if (elapsedTime == 1) {
txtTime.setText(elapsedTime + " day ago");
} else {
txtTime.setText(elapsedTime + " days ago");
}
} else if (elapsed > 3599) {
elapsedTime = elapsed / 3600;
if (elapsedTime == 1) {
txtTime.setText(elapsedTime + " hour ago");
} else {
txtTime.setText(elapsedTime + " hours ago");
}
} else if (elapsed > 59) {
elapsedTime = elapsed / 60;
txtTime.setText(elapsedTime + " min ago");
}
}
private MenuItemViewHolder.ClickListener mClickListener;
//Interface for click listener
public interface ClickListener {
void onItemClick(View view, int position);
void onItemLongClick(View view, int position);
}
public void setOnClickListener (MenuItemViewHolder.ClickListener clickListener) {
mClickListener = clickListener;
}
}
3) ListActivity
public class ListActivity extends AppCompatActivity {
List<Object> modelList = new ArrayList<>();
RecyclerView mRecyclerView;
//private AdView adView;
// The number of native ads to load and display.
public static final int NUMBER_OF_ADS = 5;
// The AdLoader used to load ads.
private AdLoader adLoader;
// List of native ads that have been successfully loaded.
private List<UnifiedNativeAd> mNativeAds = new ArrayList<>();
//layout manager for recyclerview
RecyclerView.LayoutManager layoutManager;
FloatingActionButton mAddBtn;
//firestore instance
FirebaseFirestore db;
CustomAdapter adapter;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
MobileAds.initialize(this, String.valueOf(R.string.admob_app_id));
//actionbar and its title
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("List Data");
//init firestore
db = FirebaseFirestore.getInstance();
//initialize views
mRecyclerView = findViewById(R.id.recycler_view);
mAddBtn = findViewById(R.id.addBtn);
//set Recycler views properties
mRecyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(layoutManager);
//init progree dialog
pd = new ProgressDialog(this);
//show data in recyclerView
showData();
loadNativeAds();
//Handle Floating action button to open main activity
mAddBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(ListActivity.this, MainActivity.class));
finish();
}
});
}
private void loadNativeAds() {
AdLoader.Builder builder = new AdLoader.Builder(this, getString(R.string.native_advanced_ad));
adLoader = builder.forUnifiedNativeAd(
new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
#Override
public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
// A native ad loaded successfully, check if the ad loader has finished loading
// and if so, insert the ads into the list.
mNativeAds.add(unifiedNativeAd);
if (!adLoader.isLoading()) {
insertAdsInMenuItems();
}
}
}).withAdListener(
new AdListener() {
#Override
public void onAdFailedToLoad(int errorCode) {
// A native ad failed to load, check if the ad loader has finished loading
// and if so, insert the ads into the list.
Log.e("MainActivity", "The previous native ad failed to load. Attempting to"
+ " load another.");
if (!adLoader.isLoading()) {
insertAdsInMenuItems();
//showData();
}
}
}).build();
// Load the Native Express ad.
adLoader.loadAds(new AdRequest.Builder().build(), NUMBER_OF_ADS);
}
private void insertAdsInMenuItems() {
if (mNativeAds.size() <= 0) {
return;
}
int offset = (modelList.size() / mNativeAds.size()) + 1;
int index = 3;
for (UnifiedNativeAd ad: mNativeAds) {
modelList.add(index, ad);
index = index + offset;
}
}
private void showData() {
//set tittle of progress dialog
pd.setTitle("Loading Data.......");
//show progress dialog
pd.show();
db.collection("Documents")
.orderBy("date", Query.Direction.DESCENDING)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
modelList.clear();
//called when data is retrieved
pd.dismiss();
//Show Data
for (DocumentSnapshot doc : task.getResult()) {
Model model = new Model(doc.getString("id"),
doc.getString("title"),
doc.getString("description"),
doc.getLong("time")
);
modelList.add(model);
//insertAdsInMenuItems();
}
//adapter
adapter = new CustomAdapter(ListActivity.this, modelList);
//set adapter to recyclerview
mRecyclerView.setAdapter(adapter);
//mRecyclerView.smoothScrollToPosition(adapter.getItemCount() - 1);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//called when there is any error while retrieving
pd.dismiss();
Toast.makeText(ListActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
My First issue is that the native ads wont load until I scroll the list
The list loads but ads wont load until I manually scroll through and when I click on items before scrolling my app crashes.
The native ad is supposed to appear after every three items so when I click on any item below the three items the app crashes with the logcat below.
2019-09-24 14:24:54.373 27287-27287/com.pesadevs.firebasefirestore E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.pesadevs.firebasefirestore, PID: 27287
java.lang.ClassCastException: com.google.android.gms.internal.ads.zzadl cannot be cast to com.pesadevs.firebasefirestore.Model
at com.pesadevs.firebasefirestore.CustomAdapter$1.onItemClick(CustomAdapter.java:59)
at com.pesadevs.firebasefirestore.MenuItemViewHolder$1.onClick(MenuItemViewHolder.java:21)
at android.view.View.performClick(View.java:6608)
at android.view.View.performClickInternal(View.java:6585)
at android.view.View.access$3100(View.java:782)
at android.view.View$PerformClick.run(View.java:25945)
at android.os.Handler.handleCallback(Handler.java:874)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:198)
at android.app.ActivityThread.main(ActivityThread.java:6729)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
NB: If I scroll and ads load everything works perfectly as seen in my image below.
When ads load the app works as expected.
I dont know what am doing wrong, any help would be appriciated thanks.
I created an application which pairs a cellphone to a bluetooth module.
i tested this application with a 4.2 android cellphone and it worked quite well but in cellphones with android higher than 6 the device is not fidning anything when i press " Scan for new devices " button.
but when i go through my phone bluetooth itself, i can find the module i was looking for..
Bluetooth connection class :
public class BluetoothConnectionActivity extends AppCompatActivity {
private ProgressDialog mProgressDlg;
private ArrayList<BluetoothDevice> mDeviceList = new ArrayList<BluetoothDevice>();
private BluetoothAdapter mBluetoothAdapter;
BluetoothDevice device ;
private MediaPlayer mediaplayer = null ;
private Button bluetoothOnOff;
private Button viewpairedDevices;
private Button scanfornewDevices;
private Button blue2;
ImageView unMute;
View view1;
View view2;
private Activity context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetoothconnectionlayout);
bluetoothOnOff = (Button) findViewById(R.id.bluetoothOnOff);
viewpairedDevices = (Button) findViewById(R.id.viewpairedDevicesButton);
scanfornewDevices = (Button) findViewById(R.id.scanfornewDevicesButton);
blue2 = (Button) findViewById(R.id.bluetoothOnOff2);
view1 = findViewById(R.id.viewFader);
view2 = findViewById(R.id.viewFader2);
unMute = (ImageView) findViewById(R.id.settingStartupSecondary);
mediaplayer = MediaPlayer.create(getApplicationContext(),R.raw.sfxturnon);
Handler startup1 = new Handler();
startup1.postDelayed(new Runnable() {
#Override
public void run() {
view1.animate().alpha(1f).setDuration(500);
view2.animate().alpha(1f).setDuration(500);
}
},1000);
Handler startup2 = new Handler();
startup2.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().alpha(1f).setDuration(500);
viewpairedDevices.animate().alpha(1f).setDuration(500);
scanfornewDevices.animate().alpha(1f).setDuration(500);
unMute.animate().alpha(1f).setDuration(100);
}
},1000);
//
// settingBtn.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
//
//
// AudioManager amanager=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
// amanager.setStreamMute(AudioManager.STREAM_NOTIFICATION, true);
//
//// settingBtn.setEnabled(false);
//// settingBtn.animate().alpha(0f);
//
// unMute.animate().alpha(1f);
// unMute.setEnabled(true);
//
//
// Toast.makeText(getApplicationContext(), " Application muted. ", Toast.LENGTH_SHORT).show();
//
//
// }
// });
Handler dawg = new Handler();
dawg.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().alpha(1f).setDuration(1500);
viewpairedDevices.animate().alpha(1f).setDuration(2500);
scanfornewDevices.animate().alpha(1f).setDuration(3000);
}
},500);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mProgressDlg = new ProgressDialog(this);
mProgressDlg.setMessage("Scanning, Please wait...");
mProgressDlg.setCancelable(false);
mProgressDlg.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mBluetoothAdapter.cancelDiscovery();
}
});}
if (mBluetoothAdapter.isEnabled()){
bluetoothOnOff.setText("Bluetooth is On");
blue2.setText("Bluetooth is On");
}else {
blue2.setText("Bluetooth is Off");
bluetoothOnOff.setText("Bluetooth is Off");
}
if (mBluetoothAdapter == null) {
showUnsupported();
} else {
viewpairedDevices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices == null || pairedDevices.size() == 0) {
Toast toast = Toast.makeText(getApplicationContext()," No paired device found.", Toast.LENGTH_SHORT);
View view3 = toast.getView();
view3.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view3.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
} else {
ArrayList<BluetoothDevice> list = new ArrayList<BluetoothDevice>();
list.addAll(pairedDevices);
Intent intent = new Intent(BluetoothConnectionActivity.this, DeviceList.class);
intent.putParcelableArrayListExtra("device.list", list);
startActivity(intent);
}
}
});
scanfornewDevices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mBluetoothAdapter.startDiscovery();
}
});
bluetoothOnOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
showDisabled();
bluetoothOnOff.setText("Bluetooth is OFF");
final Handler handler6 = new Handler();
handler6.postDelayed(new Runnable() {
#Override
public void run() {
mediaplayer.start();
}
}, 500);
final Handler handler3 = new Handler();
handler3.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().translationY(-1f).setDuration(5000);
blue2.animate().translationY(-1f).setDuration(5000);
bluetoothOnOff.animate().alpha(1f).setDuration(3000);
blue2.animate().alpha(0f).setDuration(3000);
}
}, 500);
} else {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1000);
}}
});
blue2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
showDisabled();
bluetoothOnOff.setText("Bluetooth is OFF");
final Handler handler6 = new Handler();
handler6.postDelayed(new Runnable() {
#Override
public void run() {
mediaplayer.start();
}
}, 500);
final Handler handler3 = new Handler();
handler3.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().translationY(-1f).setDuration(5000);
blue2.animate().translationY(-1f).setDuration(5000);
bluetoothOnOff.animate().alpha(1f).setDuration(3000);
blue2.animate().alpha(0f).setDuration(3000);
}
}, 500);
} else {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1000);
}}
});
if (mBluetoothAdapter.isEnabled()) {
showEnabled();
} else {
showDisabled();
}
}
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
}
#Override
public void onPause() {
if (mBluetoothAdapter != null) {
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
}
super.onPause();
}
#Override
public void onBackPressed() {
}
#Override
public void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
private void showEnabled() {
bluetoothOnOff.setEnabled(true);
viewpairedDevices.setEnabled(true);
viewpairedDevices.setBackgroundResource(R.drawable.selectorstylish);
scanfornewDevices.setEnabled(true);
scanfornewDevices.setBackgroundResource(R.drawable.selectorstylish);
}
private void showDisabled() {
bluetoothOnOff.setEnabled(true);
viewpairedDevices.setEnabled(false);
viewpairedDevices.setBackgroundResource(R.drawable.selectorstylish);
scanfornewDevices.setEnabled(false);
scanfornewDevices.setBackgroundResource(R.drawable.selectorstylish);
}
private void showUnsupported() {
Toast toast = Toast.makeText(getApplicationContext()," Bluetooth is not supported by this device.", Toast.LENGTH_SHORT);
View view3 = toast.getView();
view3.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view3.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
bluetoothOnOff.setEnabled(false);
viewpairedDevices.setEnabled(false);
viewpairedDevices.setBackgroundResource(R.drawable.selectorstylish);
scanfornewDevices.setEnabled(false);
scanfornewDevices.setBackgroundResource(R.drawable.selectorstylish);
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
if (state == BluetoothAdapter.STATE_ON) {
bluetoothOnOff.setText("Bluetooth is On");
blue2.setText("Bluetooth is On");
showEnabled();
final Handler handler5 = new Handler();
handler5.postDelayed(new Runnable() {
#Override
public void run() {
mediaplayer.start();
}
}, 500);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().translationY(150f).setDuration(5000);
blue2.animate().translationY(150f).setDuration(5000);
bluetoothOnOff.animate().alpha(0f).setDuration(3000);
blue2.animate().alpha(1f).setDuration(3000);
}
}, 500);
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
mDeviceList = new ArrayList<BluetoothDevice>();
mProgressDlg.show();
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
mProgressDlg.dismiss();
// Intent newIntent = new Intent(BluetoothConnectionActivity.this, DeviceList.class);
//
// newIntent.putParcelableArrayListExtra("device.list", mDeviceList);
//
// startActivity(newIntent);
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device);
Toast toast = Toast.makeText(getApplicationContext()," Found device" + device.getName(), Toast.LENGTH_SHORT);
View view3 = toast.getView();
view3.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view3.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.optionmenu,menu);
return super.onCreateOptionsMenu(menu);
}
}
Device list Class :
public class DeviceList extends AppCompatActivity {
private ListView mListView;
private AdapterClassBluetooth mAdapterClassBluetooth;
private ArrayList<BluetoothDevice> mDeviceList;
private BluetoothDevice device ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_list);
mDeviceList = getIntent().getExtras().getParcelableArrayList("device.list");
mListView = (ListView) findViewById(R.id.lv_paired);
mAdapterClassBluetooth = new AdapterClassBluetooth(this);
mAdapterClassBluetooth.setData(mDeviceList);
mAdapterClassBluetooth.setListener(new AdapterClassBluetooth.OnPairButtonClickListener() {
#Override
public void onPairButtonClick(int position) {
BluetoothDevice device = mDeviceList.get(position);
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
unpairDevice(device);
} else {
Toast toast = Toast.makeText(getApplicationContext(), "Pairing..." , Toast.LENGTH_SHORT);
View view = toast.getView();
view.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
pairDevice(device);
}
}
});
mListView.setAdapter(mAdapterClassBluetooth);
registerReceiver(mPairReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
}
#Override
public void onDestroy() {
unregisterReceiver(mPairReceiver);
super.onDestroy();
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private void pairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private void unpairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("removeBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
Toast toast = Toast.makeText(getApplicationContext()," Device are paired, please wait...", Toast.LENGTH_SHORT);
View view = toast.getView();
view.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
Handler delaying = new Handler();
delaying.postDelayed(new Runnable() {
#Override
public void run() {
Intent communicate = new Intent(DeviceList.this,Security.class);
startActivity(communicate);
finish();
}
},1500);
} else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
Toast toast = Toast.makeText(getApplicationContext(),"Unpaired.", Toast.LENGTH_SHORT);
View view = toast.getView();
view.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
}
mAdapterClassBluetooth.notifyDataSetChanged();
}
}
};}
Adapter class :
public class AdapterClassBluetooth extends BaseAdapter{
private LayoutInflater mInflater;
private List<BluetoothDevice> mData;
private OnPairButtonClickListener mListener;
public AdapterClassBluetooth(){
}
public AdapterClassBluetooth(Context context) {
super();
mInflater = LayoutInflater.from(context);
}
public void setData(List<BluetoothDevice> data) {
mData = data;
}
public void setListener(OnPairButtonClickListener listener) {
mListener = listener;
}
public int getCount() {
return (mData == null) ? 0 : mData.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.adapterlist, null);
holder = new ViewHolder();
holder.nameTv = (TextView) convertView.findViewById(R.id.tv_name);
holder.addressTv = (TextView) convertView.findViewById(R.id.tv_address);
holder.pairBtn = (Button) convertView.findViewById(R.id.btn_pair);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
BluetoothDevice device = mData.get(position);
holder.nameTv.setText(device.getName());
holder.addressTv.setText(device.getAddress());
holder.pairBtn.setText((device.getBondState() == BluetoothDevice.BOND_BONDED) ? "Unpair" : "Pair");
holder.pairBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
mListener.onPairButtonClick(position);
}
}
});
return convertView;
}
static class ViewHolder {
TextView nameTv;
TextView addressTv;
TextView pairBtn;
}
public interface OnPairButtonClickListener {
public abstract void onPairButtonClick(int position);
}
}
in an article i studied about this issue and find out that with this code :
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(context,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
1);
i can make the application to support phones with android more than 6 so i can discover all nearby devices and pair with them,
The issue is, i don't know where should i exactly use this code..
i would really appreciate if you could tell me where to use it within the codes i showed here.
or simply tell me how to overcome this problem with any other code you may know.
In your AndroidManifest.xml file add this:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Then, instead of calling registerReceiver call this function:
private tryRegisterReceiver() {
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Here, permission is not granted
// after calling requestPermissions, the result must be treated in onRequestPermissionResult
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
1000); // 100 or other desired code
} else {
// Permission has already been granted
// continue registering your receiver
registerReceiver();
}
}
To treat the result of the permission request
#Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
switch (requestCode) {
case 1000: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted
// continue registering your receiver
registerReceiver();
} else {
// permission denied
// show a message or finish your activity
}
return;
}
// other 'case' for other permissions if needed
}
}
This question already has answers here:
Android Media player play the song x times [closed]
(2 answers)
Closed 3 years ago.
How can I make this simple music player musics repeat for example 5 times or to loop the music for 1, 2, or 3 hour.
This is my code of a simple music player with a music list:
public class Musica extends AppCompatActivity implements Runnable {
private Button pause;
private Button stop;
private SeekBar mseek;
private MediaPlayer mp;
private Thread soundThread;
private Button play;
//list
AdRequest adRequest;
private AdView adView;
ListView listm;
String[] itemname = {
"music 1",
"music 2",
"music 3",
"music 4",
"music 5",
"music 6",
"Lullaby 1",
"Lullaby 2",
"Lullaby 3",
"Lullaby 4",
"Lullaby 5",
};
Integer[] imgid = {
R.drawable.musicon,
R.drawable.musicon,
R.drawable.musicon,
R.drawable.musicon,
R.drawable.musicon,
R.drawable.musicon,
R.drawable.musicon,
R.drawable.musicon,
R.drawable.musicon,
R.drawable.musicon,
R.drawable.musicon,
};
#Override
protected void onDestroy() {
super.onDestroy();
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_musica);
getSupportActionBar().hide();
adView = (AdView)findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.build();
adView.loadAd(adRequest);
adView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
adView.setVisibility(View.VISIBLE);
}
#Override
public void onAdFailedToLoad(int error) {
adView.setVisibility(View.GONE);
}
});
CustomListAdapterMusic adapter = new CustomListAdapterMusic(this, itemname, imgid);
listm = (ListView) findViewById(R.id.listmusic);
listm.setAdapter(adapter);
listm.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String Slecteditem = itemname[+position];
Toast.makeText(getApplicationContext(), Slecteditem, Toast.LENGTH_SHORT).show();
if (position == 0) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.babyone);
mp.start();
}
if (position == 1) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.babytwo);
mp.start();
}
if (position == 2) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.water);
mp.start();
}
if (position == 3) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.ocean);
mp.start();
}
if (position == 4) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.rain);
mp.start();
}
if (position == 5) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.sm);
mp.start();
}
if (position == 6) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.classica);
mp.start();
}
if (position == 7) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.relax6);
mp.start();
}
if (position == 8) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.twinkle7);
mp.start();
}
if (position == 9) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.ninar11);
mp.start();
}
if (position == 10) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.lullaby9);
mp.start();
}
play = (Button) findViewById(R.id.bplay);
pause = (Button) findViewById(R.id.bpause);
stop = (Button) findViewById(R.id.bstop);
mseek = (SeekBar) findViewById(R.id.seekBar);
setupListeners();
soundThread = new Thread(Musica.this);
soundThread.start();
}
});
}
private void stopPlaying() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
private void setupListeners()
{
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.start();
}
});
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View currentView) {
mp.stop();
}
});
mseek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
mp.seekTo(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
#Override
public void run() {
int currentPosition = 0;
int soundTotal = mp.getDuration();
mseek.setMax(soundTotal);
while (mp != null && currentPosition < soundTotal) {
try {
Thread.sleep(300);
currentPosition = mp.getCurrentPosition();
} catch (InterruptedException SoundException) {
return;
} catch (Exception otherException) {
return;
}
mseek.setProgress(currentPosition);
}
}
}
For part one, implement an setOnCompletionListener as already answered here: Android Media player play the song x times
For repeating for for 1 hour, change the counter with the timer implementation:
// get current time in milliseconds + 1 hour
long tRef = System.currentTimeMillis() + 1 * 60 * 60 * 1000L;
// set listener
mp.setOnCompletionListener(new OnCompletionListener(){
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
// current time
long tNow = System.currentTimeMillis();
if (tNow < tEnd) {
mediaPlayer.seekTo(0);
mediaPlayer.start();
}
}});
To trigger the looping again, you just need to set the tRef to a new value.
Side note: If you need both functionalities at the same time, then combine them into one listener as you cannot have two listeners on the same media player at the same time.
Alternative solution would be to set mp.setLooping() and make a timer task to turn it off, but I would not recommend it here, as it might require some lifecycle management.
Timer timerObj = new Timer();
TimerTask timerTaskObj = new TimerTask() {
public void run() {
if (mp != null) {
mp.setLooping(false)
}
}
};
timer.schedule(timerTaskObj, 0, 1 * 60 * 60 * 1000L);
I am playing audio files(MP3) by clicking on Item view, and the previous file stop automatically but the problem is that after tapping 3rd item of recyclerview the 1st one does not play sound on its click and the same problem happened on some other clicks of the list. I have added full Adapter class
public class RingToneAdapter extends RecyclerView.Adapter<RingToneAdapter.RingToneViewHolder> {
//removed declared varaible for the sake of post to edit
static final int[] resID = {R.raw.a48, R.raw.funny_hen};
public RingToneAdapter(Context rcntx, List<RingTone_Items> ringtonelist) {
this.rcntx = rcntx;
this.ringtonelist = ringtonelist;
}
#NonNull
#Override
public RingToneViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
view = LayoutInflater.from(rcntx).inflate(R.layout.ringtone_values, viewGroup, false);
RingToneViewHolder ringToneViewHolder = new RingToneViewHolder(view);
return ringToneViewHolder;
}
//playing sounds on recycler view
#Override
public void onBindViewHolder(#NonNull final RingToneViewHolder ringToneViewHolder, final int i) {
final RingTone_Items ringTone_items = ringtonelist.get(i);
ringToneViewHolder.rtv.setText(ringTone_items.getRintonetv());
if (mSelectedItem == i) {
ringToneViewHolder.iconplay.setImageResource(R.drawable.ic_pause_black_24dp);
} else {
ringToneViewHolder.iconplay.setImageResource(R.drawable.ic_play_arrow_black_24dp);
}
ringToneViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp != null && mp.isPlaying()) {
mp.stop();
mp.reset();
mp = null;
ringToneViewHolder.iconplay.setImageResource(R.drawable.ic_play_arrow_black_24dp);
}
//Intent it = new Intent(rcntx, ViewPager_Data.class);
Intent it = new Intent(rcntx, AndroidViewPagerExample.class);
it.putExtra("POS",i);
it.putExtra("name",ringTone_items.getRintonetv());
rcntx.startActivity(it);
}
});
ringToneViewHolder.iconplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mSelectedItem == i) {
mSelectedItem = -1;
oldpossssssss = i;
} else {
mSelectedItem = i;
}
notifyDataSetChanged();
if (mp != null && mp.isPlaying()) {
mp.stop();
mp.reset();
mp = null;
if (oldpossssssss == i) {
} else {
mp = new MediaPlayer();
mp = MediaPlayer.create(rcntx, resID[i]);
mp.start();
}
} else {
mp = new MediaPlayer();
mp = MediaPlayer.create(rcntx, resID[i]);
mp.start();
}
}
});
}
#Override
public int getItemCount() {
return ringtonelist.size();
}
class RingToneViewHolder extends RecyclerView.ViewHolder {
private TextView rtv, hello, close;
private ImageView iconplay;
public RingToneViewHolder(#NonNull View itemView) {
super(itemView);
rtv = itemView.findViewById(R.id.ringtitle);
iconplay = itemView.findViewById(R.id.playicon);
}
}
How can I manage this smoothly according to click the play media file accordingly. Where is I am doing wrong please help me Thanks.
I would suggest you to use singletone media player in your viewHolders. Firstly, using multiple prepared mediaPlayers are not very memory efficient. Secondly, it will allow you to resolve problems with played sound on the background because one mediaPlayer will play only one audio at a time.
ringToneViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp != null && mp.isPlaying()) {
mp.stop();
mp.reset();
mp.release();
mp = null;
ringToneViewHolder.iconplay.setImageResource(R.drawable.ic_play_arrow_black_24dp);
}
//Intent it = new Intent(rcntx, ViewPager_Data.class);
Intent it = new Intent(rcntx, AndroidViewPagerExample.class);
it.putExtra("POS",i);
it.putExtra("name",ringTone_items.getRintonetv());
rcntx.startActivity(it);
}
});
ringToneViewHolder.iconplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mSelectedItem == i) {
oldpossssssss = i;
} else {
mSelectedItem = i;
}
notifyDataSetChanged();
if (oldpossssssss == i) {
if(mp != null){
if(mp.mp.isPlaying()){
mp.pause();
} else{
mp.start();
}
}
} else {
createMediaPlayer(i)
}
}
});
Use this method when you create MediaPlayer
private void createMediaPlayer(int i)
{
if (mp!=null)
{
if(mp.isPlaying())
{
mp.stop();
mp.reset();
mp.release();
mp=null;
}
}
mp = new MediaPlayer();
mp = MediaPlayer.create(rcntx, resID[i]);
mp.start();
}
May be its work.
Realm class
public class RealmManager
private static Realm mRealm;
public static Realm open() {
mRealm = Realm.getDefaultInstance();
return mRealm;
}
public static void close() {
if (mRealm != null) {
mRealm.close();
}
}
public static RecordsDao recordsDao() {
checkForOpenRealm();
return new RecordsDao(mRealm);
}
private static void checkForOpenRealm() {
if (mRealm == null || mRealm.isClosed()) {
throw new IllegalStateException("RealmManager: Realm is closed, call open() method first");
}
}
}
When I call RealmManager.open(); my app crashes with error
Unable to open a realm at path
'/data/data/com.apphoctienganhpro.firstapp/files/default.realm':
Unsupported Realm file format version. in
/Users/cm/Realm/realm-java/realm/realm-library/src/main/cpp/io_realm_internal_SharedRealm.cpp
line 92 Kind: ACCESS_ERROR
Activity class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lesson);
ButterKnife.bind(this);
RealmManager.open();
NestedScrollView scrollView = findViewById(R.id.nest_scrollview);
scrollView.setFillViewport(true);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayShowTitleEnabled(true);
}
final CollapsingToolbarLayout collapsingToolbarLayout = findViewById(R.id.collapsing_toolbar);
AppBarLayout appBarLayout = findViewById(R.id.appbar);
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = true;
int scrollRange = -1;
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
isShow = true;
} else if (isShow) {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
isShow = false;
}
}
});
arrayListCategory = Utility.getAppcon().getSession().arrayListCategory;
arrayListGoal = Utility.getAppcon().getSession().arrayListGoal;
arrayList = new ArrayList<>();
arrayList = Utility.getAppcon().getSession().arrayListCategory;
if (arrayListGoal.size() > 0) {
goal_id = arrayListGoal.get(0).getSingleGoalId();
}else{
if(!arrayList.get(0).getCategory_description().equals("")) {
if(!Utility.getAppcon().getSession().screen_name.equals("lessson_complete")) {
displayDialog();
}
}
}
collapsingToolbarLayout.setTitle(arrayListCategory.get(0).getCategoryName());
layoutManager = new LinearLayoutManager(this);
recycler_view.setLayoutManager(layoutManager);
apiservice = ApiServiceCreator.createService("latest");
sessionManager = new SessionManager(this);
getCategoryLesson();
}
private void displayDialog() {
dialog = new Dialog(LessonActivity.this);
dialog.getWindow();
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_layout_lesson_detail);
dialog.setCancelable(true);
txt_close = dialog.findViewById(R.id.txt_close);
txt_title_d = dialog.findViewById(R.id.txt_title_d);
txt_description_d = dialog.findViewById(R.id.txt_description_d);
img_main_d = dialog.findViewById(R.id.img_main_d);
img_play_d = dialog.findViewById(R.id.img_play_d);
img_play_d.setVisibility(View.GONE);
Picasso.with(LessonActivity.this).load(ApiConstants.IMAGE_URL + arrayList.get(0).getCategoryImage())
.noFade()
.fit()
.placeholder(R.drawable.icon_no_image)
.into(img_main_d);
txt_title_d.setText(arrayList.get(0).getCategoryName());
txt_description_d.setText(Html.fromHtml(arrayList.get(0).getCategory_description().replaceAll("\\\\", "")));
dialog.show();
Window window = dialog.getWindow();
assert window != null;
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
txt_close.setOnClickListener(view -> dialog.dismiss());
}
private void getCategoryLesson() {
pDialog = new ProgressDialog(LessonActivity.this);
pDialog.setTitle("Checking Data");
pDialog.setMessage("Please Wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
Observable<LessonResponse> responseObservable = apiservice.getCategoryLesson(
sessionManager.getKeyEmail(),
arrayListCategory.get(0).getCategoryId(),
goal_id,
sessionManager.getUserData().get(0).getUserId(),
sessionManager.getKeyToken());
responseObservable.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.onErrorResumeNext(throwable -> {
if (throwable instanceof retrofit2.HttpException) {
retrofit2.HttpException ex = (retrofit2.HttpException) throwable;
Log.e("error", ex.getLocalizedMessage());
}
return Observable.empty();
})
.subscribe(new Observer<LessonResponse>() {
#Override
public void onCompleted() {
pDialog.dismiss();
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(LessonResponse lessonResponse) {
if (lessonResponse.getData().size() > 9) {
txt_total_lesson.setText(String.valueOf(lessonResponse.getData().size()));
} else {
txt_total_lesson.setText(String.valueOf("0" + lessonResponse.getData().size()));
}
if (lessonResponse.getStatusCode() == 200) {
adapter = new LessonAdapter(lessonResponse.getData(), LessonActivity.this);
recycler_view.setAdapter(adapter);
} else {
Utility.displayToast(getApplicationContext(), lessonResponse.getMessage());
}
}
});
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
#Override
public void onClickFavButton(int position, boolean toggle) {
}
public boolean isFavourate(String LessionId,String UserId){
if (arrayList!=null){
for (int i=0;i<arrayList.size();i++)
if (favarrayList.get(1).getLessonId().equals(LessionId) && favarrayList.get(0).getUserID().equals(UserId)){
return true;
}
}
return false;
}
#Override
protected void onDestroy() {
super.onDestroy();
RealmManager.close();
}
}
Adapter Class
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_lesson, parent, false);
return new LessonAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
dialog = new Dialog(context);
dialog.getWindow();
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_layout_lesson_audio);
txt_close = dialog.findViewById(R.id.txt_close);
txt_title_d = dialog.findViewById(R.id.txt_title_d);
txt_description_d = dialog.findViewById(R.id.txt_description_d);
img_play_d = dialog.findViewById(R.id.img_play_d);
frm_header = dialog.findViewById(R.id.frm_header);
img_back_d = dialog.findViewById(R.id.img_back_d);
holder.txt_lesson_title.setText(arrayList.get(position).getLessonName());
holder.btn_view.setOnClickListener(view -> {
txt_title_d.setText(arrayList.get(position).getLessonName());
dialog.show();
Window window = dialog.getWindow();
assert window != null;
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
txt_description_d.setText(Html.fromHtml(arrayList.get(position).getLessonDescription().replaceAll("\\\\", "")));
displayDialog(holder.getAdapterPosition());
});
holder.btn_go.setOnClickListener(view -> {
Utility.getAppcon().getSession().arrayListLesson = new ArrayList<>();
Utility.getAppcon().getSession().arrayListLesson.add(arrayList.get(position));
Intent intent = new Intent(context, LessonCompleteActivity.class);
context.startActivity(intent);
});
if (arrayList.get(position).isFavourate())
holder.favCheck.setChecked(true);
else
holder.favCheck.setChecked(false);
holder.favCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CheckBox checkBox = (CheckBox) view;
if (checkBox.isChecked()) {
RealmManager.recordsDao().saveToFavorites(arrayList.get(position));
} else {
RealmManager.recordsDao().removeFromFavorites(arrayList.get(position));
}
}
});
}
private void displayDialog(int Position) {
final MediaPlayer mediaPlayer = new MediaPlayer();
String url = ApiConstants.IMAGE_URL + arrayList.get(Position).getLesson_audio_url();
//String url = "http://208.91.198.96/~diestechnologyco/apphoctienganhpro/uploads/mp3/mp3_1.mp3"; // your URL here
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(url);
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare(); // might take long! (for buffering, etc)
} catch (IOException e) {
e.printStackTrace();
}
img_play_d.setOnClickListener(view -> {
if (audio_flag == 0) {
mediaPlayer.start();
audio_flag = 1;
img_play_d.setImageResource(R.mipmap.pause_circle);
} else {
mediaPlayer.pause();
audio_flag = 0;
img_play_d.setImageResource(R.mipmap.icon_play);
}
});
//img_play_d.setOnClickListener(view -> mediaPlayer.start());
txt_close.setOnClickListener(view -> {
mediaPlayer.stop();
dialog.dismiss();
});
img_back_d.setOnClickListener(view -> {
mediaPlayer.stop();
dialog.dismiss();
});
}
#Override
public int getItemCount() {
return arrayList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.txt_lesson_title)
TextView txt_lesson_title;
#BindView(R.id.txt_lesson_type)
TextView txt_lesson_type;
#BindView(R.id.btn_view)
Button btn_view;
#BindView(R.id.btn_go)
Button btn_go;
#BindView(R.id.image_favborder)
CheckBox favCheck;
ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
//RealmManager.open();
}
}
public void getdata(){
}
public void addFavourate(String LessonId,String UserId) {
if (mRealm != null) {
mRealm.beginTransaction();
favList_model = mRealm.createObject(FavList_model.class);
favList_model.setLessonId(LessonId);
favList_model.setUserID(UserId);
mRealm.commitTransaction();
mRealm.close();
}
}
}