Android Studio refresh RecyclerView item - java

I am trying to add item from one adapter into another adapter. But when I added item, doesn't appear in the another adapter's recyclerview list.
ContactDataAdapter.java
#Override
public void onBindViewHolder(final ContactDataAdapter.ViewHolder holder, int position) {
holder.titleTv.setText(arrList.get(position).toString());
holder.conIv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CallFragment cf = new CallFragment();
//CallDataAdapter cd = new CallDataAdapter();
String t = holder.titleTv.getText().toString();
cf.addItem(t.toString());
//cd.addData(t);
Toast.makeText(view.getContext(), "Added " + t, Toast.LENGTH_SHORT).show();
}
});
}
CallFragment.java
public void addItem(String title) {
adapter.addData(title.toString());
//adapter.notifyItemRangeChanged(0,data.size());
}
CallDataAdapter.java
public void addData(String title) {
dataList.add(title);
notifyDataSetChanged();
notifyItemRangeChanged(0, dataList.size());
notifyItemInserted(pos + 1);
}
The Image that clicked added button
A list that diplay added item("asd" added from the beginning.)

First setup EventBus
Define events:
public static class MessageEvent {
public String title;
}
in CallFragment declare it
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {
adapter.addData(title.toString());
};
Register in your fragment from you setup ContactDataAdapter
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
Call the event
#Override
public void onBindViewHolder(final ContactDataAdapter.ViewHolder holder, int position) {
holder.titleTv.setText(arrList.get(position).toString());
holder.conIv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MessageEvent event=new MessageEvent();
event.title= holder.titleTv.getText().toString();
EventBus.getDefault().post(event);
//CallFragment cf = new CallFragment();
//CallDataAdapter cd = new CallDataAdapter();
//String t = holder.titleTv.getText().toString();
//cf.addItem(t.toString());
//cd.addData(t);
Toast.makeText(view.getContext(), "Added " + t, Toast.LENGTH_SHORT).show();
}
});
}

Related

Load next item of reyclerview when user clicks on next button, having error in this

I am making an android app in which i have reyclerview whenever user clicks on recyclerview items then he is navigating to next activity and in next activity data will be shown. It is working but now i am adding next and previous button in it. Whenever next button will be clicked then next reycler items'data should be shown and same with previous button.
But i am getting error in this. It is my code.
RecylerAdapter:
public class ContentViewRecyclerAdapter extends RecyclerView.Adapter<ContentViewRecyclerAdapter.ViewHolder>{
ArrayList<ContentModel>contentModels;
Context context;
public ContentViewRecyclerAdapter(ArrayList<ContentModel> contentModels, Context context) {
this.contentModels = contentModels;
this.context = context;
}
#NonNull
#Override
public ContentViewRecyclerAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ContentViewRecyclerAdapter.ViewHolder holder, final int position) {
holder.textView.setText(contentModels.get(position).getContent());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, ContentViewActivity.class);
i.putExtra("valuecontent", contentModels.get(position).getContent());
i.putExtra("position", position);
i.putParcelableArrayListExtra("contentmodels", contentModels);
context.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return contentModels.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView textView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.contentText);
}
}
}
ModelClass:
public class ContentModel implements Parcelable {
String content;
public ContentModel(String content) {
this.content = content;
}
protected ContentModel(Parcel in) {
content = in.readString();
}
public static final Creator<ContentModel> CREATOR = new Creator<ContentModel>() {
#Override
public ContentModel createFromParcel(Parcel in) {
return new ContentModel(in);
}
#Override
public ContentModel[] newArray(int size) {
return new ContentModel[size];
}
};
public String getContent() {
return content;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(content);
}
}
ContentViewActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content_view);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = findViewById(R.id.adView_content);
next = findViewById(R.id.next);
prev = findViewById(R.id.prev);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
textView = findViewById(R.id.textView);
imageView = findViewById(R.id.backbtncntent);
sharebtn = findViewById(R.id.sharebtn);
copybtn = findViewById(R.id.copy);
contentModels = new ArrayList<>();
contentModels.clear();
contentModels = getIntent().getParcelableArrayListExtra("contentmodels");
final String valuecontent = getIntent().getStringExtra("valuecontent");
position = getIntent().getIntExtra("position",0);
textView.setText((Integer) contentModels.get(position));
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ContentViewActivity.this, HomeActivity.class);
startActivity(i);
}
});
sharebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Hey Read Some Interesting Content");
intent.putExtra(android.content.Intent.EXTRA_TEXT, valuecontent);
startActivity(Intent.createChooser(intent, "Share Via"));
}
});
copybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setClipboard(ContentViewActivity.this,textView.getText().toString());
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
position =(position+1)%contentModels.size();
textView.setText((Integer) contentModels.get(position));
}
});
prev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
position =(position-1)%contentModels.size();
textView.setText((Integer) contentModels.get(position));
}
});
}
private void setClipboard(Context context, String text) {
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(text);
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("Copied Text", text);
Toast.makeText(ContentViewActivity.this, "Copied to Clipboard", Toast.LENGTH_SHORT).show();
clipboard.setPrimaryClip(clip);
}
}
}
The error i am getting:
Caused by: java.lang.ClassCastException: example.example1.shayariapp.Models.ContentModel cannot be cast to java.lang.Integer
at example.example1.shayariapp.Acitivties.ContentViewActivity.onCreate(ContentViewActivity.java:54)
at android.app.Activity.performCreate(Activity.java:7227)
at android.app.Activity.performCreate(Activity.java:7218)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2941)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3066) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1764) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:202) 
at android.app.ActivityThread.main(ActivityThread.java:6962) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:528) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:888) 
Please please help me to solve this issue. Please
It is located here:
textView.setText((Integer) contentModels.get(position));
You are trying to parse ContentModel item into Integer.
You are doing this 3 times. Inside onCreate() and inside ClickListeners for next and prev.

how to delete cardview in a recycler view and its json data

I want to delete card in a RecyclerView after selecting it.data in the RecyclerView is JSON data
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
if(response.isSuccessful()) {
JsonObject responseObject = response.body();
if (responseObject.has("data")) {
JsonArray arrayobject = responseObject.getAsJsonArray("data");
ArrayList<User_Details_Model> myorder = getGeneral(arrayobject.toString());
viewRequestControllerCallback.hitsuccess1(myorder);
Here is a good resource to detect which cardView is clicked. After clicking a cardView you can delete it:
Recyclerview-listener
public interface OnItemClickListener {
void onItemClick(ContentItem item);
}
public void bind(final ContentItem item, final OnItemClickListener listener) {
...
itemView.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
listener.onItemClick(item);
}
});
}
this is the adapter
public void onBindViewHolder(#NonNull final UserViewHolder holder, final int
position) {
final User_Details_Model product = user_details.get(position);
Log.d("######",user_details.toString());
holder.tv1.setText(product.getDriverId());
holder.tv2.setText(product.getDriverName());
holder.tv3.setText(product.getVehicleId());
holder.tv4.setText(product.getVehicleType());
holder.tv5.setText(product.getOilType());
holder.button_ok.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
int pos=holder.getAdapterPosition();
if (position==pos){
getdetails();
user_details.remove(pos);
}
}
}

Update TAB 2 Recyclerview When Data Added in TAB 1's RecyclerView

I have kind of to-do app. In profile activity, there are 2 tabs.
To-do and Done. In Tab 1, user can check as "done" of their "to-do". In this case, I want to update TAB 2's recyclerview.
I tried several things, but didn't work. Here is TAB 1 codes, it's almost same as TAB 2.
TAB 1 Class
public class Tab_Profile_1 extends Fragment {
private RecyclerView recyclerView_tab_todo;
private List<Model_ListItem> itemList;
private Adapter_Profile_ToDo adapter_profile_toDo;
SharedPreferences mSharedPref;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile_tab_1, container, false);
//TO-DO
//
recyclerView_tab_todo = view.findViewById(R.id.recyclerView_tab_todo);
//
fetchUserToDo();
return view;
}
public void fetchUserToDo() {
itemList = new ArrayList<>();
//First Settings
mSharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
String session_user_id = mSharedPref.getString("session_user_id", "");
API_Service api_service = Client.getRetrofitInstance().create(API_Service.class);
Call<List<Model_ListItem>> call = api_service.fetchUserToDo(session_user_id);
call.enqueue(new Callback<List<Model_ListItem>>() {
#Override
public void onResponse(Call<List<Model_ListItem>> call, Response<List<Model_ListItem>> response) {
itemList = response.body();
adapter_profile_toDo = new Adapter_Profile_ToDo(getContext(), itemList);
recyclerView_tab_todo.setHasFixedSize(true);
LinearLayoutManager layoutManager
= new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
recyclerView_tab_todo.setLayoutManager(layoutManager);
recyclerView_tab_todo.setAdapter(adapter_profile_toDo);
}
#Override
public void onFailure(Call<List<Model_ListItem>> call, Throwable t) {
}
});
}}
TAB 1 RecyclerView Adapter
public class Adapter_Profile_ToDo extends RecyclerView.Adapter {
private Context context;
private List<Model_ListItem> itemList;
private String url_extension_images = URL_Extension.url_extension_images;
SharedPreferences mSharedPref;
ProgressDialog progressDialog;
View view;
public Adapter_Profile_ToDo(Context context, List<Model_ListItem> itemList) {
this.context = context;
this.itemList = itemList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_profile_todo, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
Glide.with(context).load(url_extension_images + itemList.get(position).getItem_image()).into(holder.imageView_profile_todo);
holder.textView_profile_todo_name.setText(itemList.get(position).getItem_name());
holder.textView_profile_todo_desc.setText(itemList.get(position).getItem_description());
holder.layout_profile_todo_detail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//detail
}
});
holder.layout_profile_todo_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder builder = new AlertDialog.Builder(view.getRootView().getContext(), R.style.AlertStyle);
builder.setTitle("\"" + itemList.get(position).getItem_name() + "\"" + "\n");
builder.setIcon(R.drawable.ic_bookmark);
builder.setPositiveButton("YAPTIM", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
showProgressDialog();
addDone("" + itemList.get(position).getItem_id(), position);
}
});
builder.setNegativeButton("SİL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
showProgressDialog();
deleteUserToDo("" + itemList.get(position).getItem_id(), position);
}
});
builder.setNeutralButton("İptal", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
});
}
#Override
public int getItemCount() {
return itemList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView_profile_todo;
TextView textView_profile_todo_name, textView_profile_todo_desc;
LinearLayout layout_profile_todo_detail, layout_profile_todo_add;
public ViewHolder(View itemView) {
super(itemView);
imageView_profile_todo = itemView.findViewById(R.id.imageView_profile_todo);
textView_profile_todo_name = itemView.findViewById(R.id.textView_profile_todo_name);
textView_profile_todo_desc = itemView.findViewById(R.id.textView_profile_todo_desc);
layout_profile_todo_detail = itemView.findViewById(R.id.layout_profile_todo_detail);
layout_profile_todo_add = itemView.findViewById(R.id.layout_profile_todo_add);
}
}
public void deleteUserToDo(final String listId, final int clicked) {
mSharedPref = PreferenceManager.getDefaultSharedPreferences(context);
String session_user_id = mSharedPref.getString("session_user_id", "");
API_Service api_service = Client.getRetrofitInstance().create(API_Service.class);
Call<Response_Success> call = api_service.deleteUserToDo(session_user_id, listId);
call.enqueue(new Callback<Response_Success>() {
#Override
public void onResponse(Call<Response_Success> call, Response<Response_Success> response) {
if (response.code() == 200) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
if (response.body().getSuccess().matches("true")) {
Toast.makeText(context, "Silindi!", Toast.LENGTH_SHORT).show();
itemList.remove(itemList.get(clicked));
notifyItemRemoved(clicked);
notifyItemRangeChanged(clicked, itemList.size());
} else {
Toast.makeText(context, "Bilinmeyen bir hata oluştu!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onFailure(Call<Response_Success> call, Throwable t) {
Toast.makeText(context, "Bilinmeyen bir hata oluştu!", Toast.LENGTH_SHORT).show();
}
});
}
public void addDone(String listId, final int clicked) {
mSharedPref = PreferenceManager.getDefaultSharedPreferences(context);
String session_user_id = mSharedPref.getString("session_user_id", "");
API_Service apiService = Client.getRetrofitInstance().create(API_Service.class);
Call<Response_Success> call = apiService.addDone(session_user_id, listId);
call.enqueue(new Callback<Response_Success>() {
#Override
public void onResponse(Call<Response_Success> call, Response<Response_Success> response) {
if (response.code() == 200) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
if (response.body().getSuccess().matches("true")) {
Toast.makeText(context, "Eklendi", Toast.LENGTH_SHORT).show();
itemList.remove(itemList.get(clicked));
notifyItemRemoved(clicked);
notifyItemRangeChanged(clicked, itemList.size());
} else {
Toast.makeText(context, "Bilinmeyen bir hata oluştu!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onFailure(Call<Response_Success> call, Throwable t) {
}
});
}
public void showProgressDialog() {
progressDialog = new ProgressDialog(view.getRootView().getContext());
progressDialog.setMessage("Yükleniyor");
progressDialog.setCancelable(false);
progressDialog.show();
}
}
If i'm reading this correctly, you have two tabs and a backend database that stores the to do items and their state? To get the second list to update, you just need to do the same thing that you're doing in your first list, and update the adapter's data set and notify that the data set changed. How you trigger this action in your second tab is really the question.
You can either use an interface and have your adapter notify your activity that recycler view 1 had an action on it, and you can then tell adapter 2 to update its data. You can either pass back the data and only notify one row, or you could notify the entire data set. If you're doing this all service based, you could just reload the recycler view from the service and it will have the new data.
I think all you need to figure out is how you want to notify tab 2 that it needs to update its data. My recommendation is:
public interface AdapterInterface
{
void itemCompleted(Item hereIsTheItemThatNeedsToBeAddedTo2);
}
Then inside your adapter have a property with getters/setters such as:
private AdapterInterface adapterInterfaceListener;
Inside your Fragment/Activity implement AdapterInterface and implement the itemCompleted function.
And then set your adapter.setAdapterInterfaceLisetener to that function that you implemented. Then inside your adapter when the user clicks the checkbook to mark it as done, you can call the adapterInterfaceListener.itemCompleted() function, and it will send that information to your Fragment/Activity. From there you can give that new data to adapter2, or recall the API, however you want to get the new data.
Does this help?

getRef(position).getKey() in RecyclerView.Adapter

In FirebaseRecyclerAdapter I can use the getRef(position).getKey() but I am using a RecyclerView.Adapter and I want get the key whenever the user click the checkbox. Here is my code in onBindViewHolder():
#Override
public void onBindViewHolder(#NonNull UsersViewHolders holder, final int position) {
holder.setName(mUserNameList.get(position));
holder.setDesc(mUserDescList.get(position));
holder.setImage(mUserPicList.get(position));
holder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//TODO: get the key
}
});
}
Is it possible to get the key in RecyclerView.Adapter?
I manage to solved my own question just by reconstructing my code.
1. In the adapter class, I created an interface for itemClickListener
public interface RecyclerViewItemClick {
public void OnItemClickListener(UsersViewHolders holder, int position);
}
and create a global
private RecyclerViewItemClick mListener;
add it to constructor
public MessageListAdapter(RecyclerViewItemClick listener) {
this.mListener = listener;
}
2. In onBindViewHolder() I passed the holder and the position
#Override
public void onBindViewHolder(#NonNull final UsersViewHolders holder, final int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.OnItemClickListener(holder, position);
}
});
}
3. In your activity, add this code. Declare a global variable for ArrayList to store the keys and call the addListenerForSingleValueEvent to your DatabaseReference
//mUserDatabase is a DatabaseReference
mUserDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
String uid = datas.getKey();
//mUserKey is an ArrayList<String>
mUserKey.add(uid);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
4. Now add this to get the key for every position
mAdapter = new MyAdapter(new MyAdapter.RecyclerViewItemClick() {
#Override
public void OnItemClickListener(PickMemberAdapter.UsersViewHolders holder, int position) {
String userKey = mUserKey.get(position);
if (!holder.mCheckBox.isChecked()) {
holder.mCheckBox.setChecked(true);
Toast.makeText(MainActivity.this, userKey, Toast.LENGTH_LONG).show();
} else {
holder.mCheckBox.setChecked(false);
Toast.makeText(MainActivity.this, userKey, Toast.LENGTH_LONG).show();
}
}
});

New bie : Why is this code not able to read anything from the firebase database

The Following is my main activity, in another activity the user can login and upload audio files to the firebase storage; after that it saves the link and the current date time in the firebase database in reverse order.
The structure of the database is Audios> Feb 26,2018> "http:// link to firebase storage"
What I am trying to achieve in this activity is to read the link from the database> Store the value in the string value> and play it on mediaplayer but the following code is not able to read the link from the database for the life of me Please help me I am a new bie
package com.shresthawebworks.dailydevotional;
public class MainActivity extends AppCompatActivity implements MediaPlayer.OnPreparedListener{
private MediaPlayer mMediaplayer;
private ImageButton dplayButton;
private ImageButton dpauseButton;
private ImageButton dstopButton;
private SeekBar seekBar;
private Handler handler;
private Runnable runnable;
private TextView durl;
private TextView drealurl;
private String currentDateTimeString = DateFormat.getDateInstance().format(new Date());
private static final String TAG = null;
private String value = "Udated";
FirebaseDatabase database = FirebaseDatabase.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dplayButton = findViewById(R.id.playButton);
dpauseButton = findViewById(R.id.pauseButton);
dstopButton = findViewById(R.id.stopButton);
durl = findViewById(R.id.dateString);
drealurl = findViewById(R.id.urlText);
handler = new Handler();
seekBar = findViewById(R.id.seekBar1);
mMediaplayer = new MediaPlayer();
mMediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
DatabaseReference myRef = database.getReference("Audios");
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
value = (String) dataSnapshot.child(currentDateTimeString).getValue();
// do your stuff here with value
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
fetchAudioUrlFromFirebase();
//.setDataSource();
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean input) {
if (input){
mMediaplayer.seekTo(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
configureNextButton();}
public void playCycle(){
seekBar.setProgress(mMediaplayer.getCurrentPosition());
if (mMediaplayer.isPlaying()){
runnable =new Runnable() {
#Override
public void run() {
playCycle();
}
};
handler.postDelayed(runnable,1000);
}
}
#Override
protected void onResume() {
super.onResume();
// mMediaplayer.resu;
playCycle();
}
#Override
protected void onPause() {
super.onPause();
mMediaplayer.pause();
playCycle();
}
#Override
protected void onDestroy() {
super.onDestroy();
mMediaplayer.release();
handler.removeCallbacks(runnable);
}
private void fetchAudioUrlFromFirebase() {
final FirebaseStorage storage = FirebaseStorage.getInstance();
durl.setText(currentDateTimeString);
drealurl.setText(value);
// Create a storage reference from our app
StorageReference storageRef = storage.getReferenceFromUrl("https://firebasestorage.googleapis.com/v0/b/dailydevotional-9f982.appspot.com/o/audios%2Ftwoprincess.mp3?alt=media&token=e3f98223-68e8-461a-8452-54eca96af4fd");
storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
try {
// Download url of file
final String url = uri.toString();
mMediaplayer.setDataSource(url);
// wait for media player to get prepare
mMediaplayer.setOnPreparedListener(MainActivity.this);
mMediaplayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.i("TAG", e.getMessage());
}
});
}
#Override
public void onPrepared(final MediaPlayer mp) {
dplayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
seekBar.setMax(mp.getDuration());
mp.start();
playCycle();
}
});
dpauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.pause();
}
});
dstopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
playCycle();
mp.stop();
mp.reset();
//fetchAudioUrlFromFirebase();
}
});
}
private void configureNextButton(){
ImageButton dButton= (ImageButton) findViewById(R.id.starLogin);
dButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, UploadActivity.class));
}
});
}
}

Categories

Resources