stop progressbar from another class when it started from mainActivity - android

Is there any way to stop the progress bar from other class which is started in mainActivity
Kindly find the code
I am starting the progress bar in the main activity and then calling the method of other java class
where I am inserting data in firebase
I just want that after firebase insertion is successful progress bar should stop
but didn't find any way to do that
public class ProductDetails extends AppCompatActivity {
ProgressBar progressbar;
Button btn;
FirebaseDatabase firebaseDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_details);
progressbar = findViewById(R.id.btnprogressbar);
btn = findViewById(R.id.submit_btn);
firebaseDatabase = FirebaseDatabase.getInstance();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressbar.setVisibility(View.VISIBLE);
submitForm();
}
});
}
private void submitForm() {
FormDetailsServices formDetailsServices = new FormDetailsServices(ProductDetails.this);
FormDTO formDTO=generateForDTO();
formDetailsServices.submitForm(formDTO,firebaseDatabase);
}
}
My FormDetailsServices:
public class FormDetailsServices {
Context context;
final String TAG = "FormDetailsServices";
public FormDetailsServices(Context context) {
this.context = context;
}
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
public void submitForm(FormDTO formDTO,FirebaseDatabase firebaseDatabase) {
firebaseDatabase
.getReference()
.child("test")
.setValue(formDTO)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG,"form submitted Successfully");
//here i want to stop progressbar
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG,"form submittion Failed exception msg= " + e.getMessage());
}
});
}
}
Everything is working fine its getting inserted to Firebase but progressbar is still visible

You can create an interface in FormDetailsServices class and implement it to your main class, and then you can hide the progress bar by calling its methods in main class as below -
public class ProductDetails extends AppCompatActivity implements FormDetailsServices.OnFormSubmissionListener{
ProgressBar progressbar;
Button btn;
FirebaseDatabase firebaseDatabase;
OnFormSubmissionListener listener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_details);
progressbar = findViewById(R.id.btnprogressbar);
btn = findViewById(R.id.submit_btn);
firebaseDatabase = FirebaseDatabase.getInstance();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressbar.setVisibility(View.VISIBLE);
submitForm();
}
});
}
private void submitForm() {
FormDetailsServices formDetailsServices = new
FormDetailsServices(ProductDetails.this);
formDetailsServices.setOnFormSubmissionListener(this);
FormDTO formDTO=generateForDTO();
formDetailsServices.submitForm(formDTO,firebaseDatabase);
}
#Override
public void onSubmissionSuccess() {
progressbar.setVisibility(View.GONE);
}
#Override
public void onSubmissionFailure() {
progressbar.setVisibility(View.GONE);
}
}
and for FormDetailsServices
public class FormDetailsServices {
Context context;
final String TAG = "FormDetailsServices";
OnFormSubmissionListener listener;
public FormDetailsServices(Context context) {
this.context = context;
}
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
void setOnFormSubmissionListener(OnFormSubmissionListener listener){
this.listener = listener;
}
public void submitForm(FormDTO formDTO,FirebaseDatabase firebaseDatabase) {
firebaseDatabase
.getReference()
.child("test")
.setValue(formDTO)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG,"form submitted Successfully");
//here i want to stop progressbar
listener.onSubmissionSuccess();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
listener.onSubmissionFailure();
Log.d(TAG,"form submittion Failed exception msg= " + e.getMessage());
}
});
}
interface OnFormSubmissionListener {
void onSubmissionSuccess();
void onSubmissionFailure();
}
}

Related

android viewpager2 page buton controller

if the page is loaded, the button is active, if not, how can I do passive control?
What I want to do is, if the Viewpager Page is loaded, the button is active, if not, the Button is Passive. But I couldn't do any kind.
Is there anyone who can help?
If viewpager2 is installed Button enabled, if viewpager2 is not installed button false;
List<Movie> movieList = new ArrayList<>();
private ImageButton btn_down, btn_fav;
private Button btn_setter;
private DatabaseReference movies;
private IFirebaseLoadDone iFirebaseLoadDone;
public CartoonFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_cartoon, container, false);
movies = FirebaseDatabase.getInstance().getReference("Sports");
movies.keepSynced(true);
iFirebaseLoadDone = this;
loadMovie();
viewPager2 = view.findViewById(R.id.viewPager2_);
btn_down = view.findViewById(R.id.btn_down);
btn_setter = view.findViewById(R.id.btn_setter);
btn_fav = view.findViewById(R.id.btn_fav);
btn_down.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SaveToGallery();
}
});
btn_setter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
btn_fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return view;
}
private void loadMovie() {
movies.addValueEventListener(this);
}
#Override
public void onFirebaseLoadSuccess(List<Movie> movieList) {
viewPagerAdapter = new ViewPagerAdapter(getContext(), movieList, viewPager2);
viewPager2.setAdapter(viewPagerAdapter);
}
#Override
public void onFirebasLoadFailed(String message) {
}
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot moviesSnapShot : dataSnapshot.getChildren())
movieList.add(moviesSnapShot.getValue(Movie.class));
Collections.reverse(movieList);
iFirebaseLoadDone.onFirebaseLoadSuccess(movieList);
viewPagerAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
iFirebaseLoadDone.onFirebasLoadFailed(databaseError.getMessage());
}
#Override
public void onDestroy() {
movies.removeEventListener(this);
super.onDestroy();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onStop() {
movies.removeEventListener(this);
super.onStop();
}
}
Replace your methods with mine.
private void loadMovie() {
movies.addValueEventListener(this);
btn_down.setEnabled(false);
btn_fav.setEnabled(false);
btn_setter.setEnabled(false);
}
Firebase methods
#Override
public void onFirebaseLoadSuccess(List<Movie> movieList) {
viewPagerAdapter = new ViewPagerAdapter(getContext(), movieList, viewPager2);
viewPager2.setAdapter(viewPagerAdapter);
if(movieList!=null && !movieList.isEmpty()){
btn_down.setEnabled(true);
btn_fav.setEnabled(true);
btn_setter.setEnabled(true);
}
}
#Override
public void onFirebasLoadFailed(String message) {
btn_down.setEnabled(false);
btn_fav.setEnabled(false);
btn_setter.setEnabled(false);
}
There was an error loading
private void loadMovie() {
movies.addValueEventListener(this);
btn_down.setEnabled(false);
btn_fav.setEnabled(false);
btn_setter.setEnabled(false);
}
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setEnabled(boolean)' on a null object reference
at com.example.duvarlar.Fragment.CartoonFragment.loadMovie(CartoonFragment.java:386)
at com.example.duvarlar.Fragment.CartoonFragment.onCreateView(CartoonFragment.java:90)

How to use "onClickListener" in MPV in android?

I use mvp architecture.
I have the setupViews () method in which the buttons and ... are defined
how i can use setOnclickListener for Button in "presenter" and call it in SetupViews in "activity".
I do not want to use it directly in "view",I want to tell the presenter that the click is done and the presenter will do the job.
My interface:
public interface HomeContract {
interface View extends BaseView {
void showNews(List<News> newsList);
void showError(String error);
}
interface Presenter extends BasePresenter<View> {
void getNewsList();
} }
presenter class :
public class HomePresenter implements HomeContract.Presenter {
private HomeContract.View view;
private NewsDataSourse newsDataSourse;
CompositeDisposable compositeDisposable = new CompositeDisposable();
public HomePresenter(NewsDataSourse newsDataSourse) {
this.newsDataSourse = newsDataSourse;
}
#Override
public void getNewsList() {
newsDataSourse.getNews().subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<List<News>>() {
#Override
public void onSubscribe(Disposable d) {
compositeDisposable.add(d);
}
#Override
public void onSuccess(List<News> news) {
view.showNews(news);
}
#Override
public void onError(Throwable e) {
view.showError(e.toString());
}
});
}
#Override
public void attachView(HomeContract.View view) {
this.view = view;
getNewsList();
}
#Override
public void detachView() {
this.view = null;
if (compositeDisposable != null && compositeDisposable.size() > 0) {
compositeDisposable.clear();
}
}}
my view :
public class HomeActivity extends BaseActivity implements HomeContract.View {
private HomeContract.Presenter presenter;
private NewsRepository newsRepository = new NewsRepository();
private RecyclerView recyclerView;
private RecyclerAdapter recyclerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
presenter = new HomePresenter(newsRepository);
}
#Override
public void setupViews() {
Button btn_Ok = (Button) findViewById(R.id.btn_Ok);
recyclerView = (RecyclerView) findViewById(R.id.recycler);
recyclerView.setLayoutManager(new LinearLayoutManager(getViewContext(), LinearLayout.VERTICAL, false));
// btn_Ok.setOnClickListener();
}
#Override
public void showNews(List<News> newsList) {
setupViews();
recyclerView.setAdapter(new RecyclerAdapter(newsList, getViewContext()));
if (newsList.size() > 0) {
Toast.makeText(getViewContext(), "ok", Toast.LENGTH_SHORT).show();
Toast.makeText(getViewContext(), newsList.get(0).getName(), Toast.LENGTH_SHORT).show();
} else
Toast.makeText(getViewContext(), "not Ok", Toast.LENGTH_SHORT).show();
}
#Override
public void showError(String error) {
Toast.makeText(getViewContext(), error, Toast.LENGTH_SHORT).show();
}
#Override
public Context getViewContext() {
return getApplicationContext();
}
#Override
protected void onStart() {
super.onStart();
presenter.attachView(this);
}
#Override
protected void onStop() {
super.onStop();
presenter.detachView();
}
}
i want to use btn_Ok.setOnClickListener(presenter....); in view Or any better solution you need to do this
In your presenter interface type a method :
interface Presenter extends BasePresenter<View> {
void getNewsList();
void onButtonClicked();
}
And than in your HomePresenter class use it :
#Override
public void onButtonClicked(){
// continue logic here
}
If you don't override it the class will show an error

how to write a variable from a singleton in firebase

There is a program where I can change a variable using a singleton. Created 2 activites, where users can change this variable. How to write the variable that is being changed to the Firebase database. I tried to use the addValueEventListener (new ValueEventListener () method.
Where do I use the firebase methods? In the main class or in singleton? And how to write a variable?
main activity
public class MainActivity extends AppCompatActivity {
private BubbleWrap bubbleWrap;
private TextView txtintent;
final int REQUEST_CODE_661_1 = 1;
private int bbbbb;
private TextView txt;
private String bubul;
FirebaseDatabase database=FirebaseDatabase.getInstance();
final DatabaseReference AllFacebase =database.getReference("всего").child("йй");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt=findViewById(R.id.textView);
bubbleWrap=BubbleWrap.getInstance();
setupAddMoreButton();
setupPopActivityButton();
setupCocActivityButton();
txtintent=(TextView)findViewById(R.id.txtintent);
AllFacebase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
bubul=String.valueOf(dataSnapshot.getValue());
txtintent.setText(bubul);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
protected void onResume() {
super.onResume();
updateUI();
}
private void setupAddMoreButton(){
Button btn=findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bubbleWrap.addMoreBubbles();
updateUI();
}
});
}
private void setupPopActivityButton(){
Button btn=findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void setupCocActivityButton(){
Button btn=findViewById(R.id.buttoncoc);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void updateUI(){
txtintent.setText(String.format(Locale.getDefault(),"%d",
bubbleWrap.getNumBubbles()));
}
}
second activity
activity, where I change the variable, I want to write to Firebase
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pop);
bubbleWrap=BubbleWrap.getInstance();
final TextView txt=findViewById(R.id.textView2);
setupPopButton();
updateUI();
Intent intent=new Intent();
intent.putExtra("bubles", bubbleWrap.getNumBubbles());
}
private void setupPopButton(){
Button btn=findViewById(R.id.cocbtb);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bubbleWrap.popBubble();
updateUI();
}
});
}
private void updateUI(){
TextView txt=findViewById(R.id.textView2);
txt.setText(String.format(Locale.getDefault(),
"Bubbles left: %d",
bubbleWrap.getNumBubbles()));
}
}
Singleton
public class BubbleWrap {
private static final int ADD_MORE_BUBBLES = 10;
private int numBubbles;
private static BubbleWrap instance;
private BubbleWrap(){
}
public static BubbleWrap getInstance(){
if(instance==null){
instance=new BubbleWrap();
}
return instance;
}
public int getNumBubbles() {
return numBubbles;
}
public void addMoreBubbles(){
numBubbles+=ADD_MORE_BUBBLES;
}
public void popBubble() {
numBubbles--;
}
public void saveintent(){
}
}

how to replace AsyncTask by RxAndroid

I am trying to use RxAndroid to do the same work which is AsyncTask exactly does. I coded a simple example, where I enter a n integer in an edittext and when I press
a button, I make the hread to sleep for 3 seconds using "SystemClock.sleep" and while the thread is sleeping I show a progressbar and when the three seconds
elapsed the progresssbar will adisappear and the value entered in the edittext will be multiplied by 10 and displayed in atextview.
normally, when I use AsyncTask, I show the progressbar in onPreExecute and make it to disappear in onPostExecute. but when I run the below code I receive the
following error:
Only the original thread that created a view hierarchy can touch its views.
how to handle it properly in RxAndroid?
code:
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private EditText mEditTextValueToProcess = null;
private Button mButtonGoAsynchronous = null;
private TextView mTextViewProcessedValue = null;
private ProgressBar mProgressBar = null;
private rx.Observable<String> mAsyncObservable = null;
Subscriber mAsyncSubscriber = new Subscriber<String>() {
#Override
public void onCompleted() {
Log.w(TAG, "onCompleted");
mProgressBar.setVisibility(View.GONE);
}
#Override
public void onError(Throwable e) {
Log.w(TAG, "onError: " + e.getMessage().toString());
mProgressBar.setVisibility(View.GONE);
}
#Override
public void onNext(String o) {
Log.w(TAG, "onNext:->after processing " + o);
mTextViewProcessedValue.setText(o);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intiViews();
mAsyncObservable = rx.Observable.create(new rx.Observable.OnSubscribe<String>() {
#Override
public void call(Subscriber<? super String> subscriber) {
mProgressBar = (ProgressBar) findViewById(R.id.progressDialog);
mProgressBar.setVisibility(View.VISIBLE);
SystemClock.sleep(3000);
subscriber.onNext("" + Integer.valueOf(mEditTextValueToProcess.getText().toString()) * 10);
subscriber.onCompleted();
}
});
}
private void intiViews() {
mEditTextValueToProcess = (EditText) findViewById(R.id.edittext);
mButtonGoAsynchronous = (Button) findViewById(R.id.button_go_asynchronous);
mTextViewProcessedValue = (TextView) findViewById(R.id.textview_processed_value);
//mProgressBar = (ProgressBar) findViewById(R.id.progressDialog);
mButtonGoAsynchronous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAsyncObservable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(mAsyncSubscriber);
}
});
}
}
Have you tried
private Observable<String> createObservable(final int number) {
return rx.Observable.create(new rx.Observable.OnSubscribe<String>() {
#Override
public void call(Subscriber<? super String> subscriber) {
SystemClock.sleep(3000);
subscriber.onNext("" + number * 10);
subscriber.onCompleted();
}
});
}
private void intiViews() {
mEditTextValueToProcess = (EditText) findViewById(R.id.edittext);
mButtonGoAsynchronous = (Button) findViewById(R.id.button_go_asynchronous);
mTextViewProcessedValue = (TextView) findViewById(R.id.textview_processed_value);
mProgressBar = (ProgressBar) findViewById(R.id.progressDialog);
mButtonGoAsynchronous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProgressBar.setVisibility(View.VISIBLE);
createObservable(Integer.valueOf(mEditTextValueToProcess.getText().toString()))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext((ignored) -> {
mProgressBar.setVisibility(View.GONE);
})
.subscribe(mAsyncSubscriber);
}
});
}
?
You need to change few things to achieve this. Look at mAsyncSubscriber initialization, onStart() method & progressBar initialization. The reason why you are getting the error is you are initializing & making your progressbar visible in another thread then your UI thread (because you specified this -> subscribeOn(Schedulers.io()).
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private EditText mEditTextValueToProcess = null;
private Button mButtonGoAsynchronous = null;
private TextView mTextViewProcessedValue = null;
private ProgressBar mProgressBar = null;
private rx.Observable<String> mAsyncObservable = null;
Subscriber mAsyncSubscriber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intiViews();
mAsyncSubscriber = new Subscriber<String>() {
// Override onStart method
#Override
public void onStart() {
mProgressBar.setVisibility(View.VISIBLE);
}
#Override
public void onCompleted() {
Log.w(TAG, "onCompleted");
mProgressBar.setVisibility(View.GONE);
}
#Override
public void onError(Throwable e) {
Log.w(TAG, "onError: " + e.getMessage().toString());
mProgressBar.setVisibility(View.GONE);
}
#Override
public void onNext(String o) {
Log.w(TAG, "onNext:->after processing " + o);
mTextViewProcessedValue.setText(o);
}
};
mAsyncObservable = rx.Observable.create(new rx.Observable.OnSubscribe<String>() {
#Override
public void call(Subscriber<? super String> subscriber) {
SystemClock.sleep(3000);
subscriber.onNext("" + Integer.valueOf(mEditTextValueToProcess.getText().toString()) * 10);
subscriber.onCompleted();
}
});
}
private void intiViews() {
// Init your progressbar
mProgressBar = (ProgressBar) findViewById(R.id.progressDialog);
mEditTextValueToProcess = (EditText) findViewById(R.id.edittext);
mButtonGoAsynchronous = (Button) findViewById(R.id.button_go_asynchronous);
mTextViewProcessedValue = (TextView) findViewById(R.id.textview_processed_value);
//mProgressBar = (ProgressBar) findViewById(R.id.progressDialog);
mButtonGoAsynchronous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAsyncObservable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(mAsyncSubscriber);
}
});
}

Can't filter Firebase data with order by child

I want to show Firebase data filtered by userID. But the app crashes and after debugging it shows a NullPointerException on the Firebase adapter. What to do? I am implementing it in fragment. I am not pasting the imported libraries.
Here is my code:
public class MyPosts extends Fragment{
private RecyclerView postList;
private DatabaseReference mDatabase;
private DatabaseReference mDatabaseAppriciate;
private DatabaseReference mDatabaseDisgrace;
private LinearLayoutManager layoutManager;
private FirebaseAuth mAuth= FirebaseAuth.getInstance();
private DatabaseReference mDatabaseCurrentUser;
public Query mQueryCurrentUser=null;
//private static final String TAG = "MyActivity";
private boolean mProcessAppriciate=false;
private boolean mProcessDisgrace=false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
View rootView = inflater.inflate(R.layout.allposts, container, false);
mDatabase= FirebaseDatabase.getInstance().getReference().child("Posts");
mDatabaseAppriciate=FirebaseDatabase.getInstance().getReference().child("Appriciate");
mDatabaseDisgrace=FirebaseDatabase.getInstance().getReference().child("Disgrace");
mDatabase.keepSynced(true);
mDatabaseAppriciate.keepSynced(true);
mDatabaseDisgrace.keepSynced(true);
//EXPERIMENT WITH LISTVIEW STARTS
postList=(RecyclerView) rootView.findViewById(R.id.postList);
postList.setHasFixedSize(true);
layoutManager=new LinearLayoutManager(getActivity());
layoutManager.setReverseLayout(true);
postList.setHasFixedSize(true);
postList.setLayoutManager(layoutManager);
postList.getRecycledViewPool().clear();
//EXPERIMENT WITH LISTVIEW ENDS
return rootView;
}
#Override
public void onStart() {
super.onStart();
//EXP CODE STARTS
FirebaseAuth.getInstance().addAuthStateListener(new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
mDatabaseCurrentUser=FirebaseDatabase.getInstance().getReference().child("Posts");
String currentUserId=user.getUid();
mQueryCurrentUser=mDatabaseCurrentUser.orderByChild("uid").equalTo(currentUserId);
}else{
}
}
});
//EXP CODE ENDS
FirebaseRecyclerAdapter<Posts,PostViewHolder> firebaseRecyclerAdapter= new FirebaseRecyclerAdapter<Posts,PostViewHolder>(
Posts.class,
R.layout.single_post,
PostViewHolder.class,
mQueryCurrentUser
) {
#Override
protected void populateViewHolder(final PostViewHolder viewHolder, final Posts model, final int position) {
final String post_key=getRef(position).getKey();
viewHolder.setTitle(model.getTitle());
viewHolder.setDescription(model.getDescription());
viewHolder.setProfileName(model.getProfilename());
viewHolder.setImage(getContext(),model.getImage());
viewHolder.getLayoutPosition();
viewHolder.setAppriciateButton(post_key);
viewHolder.setDisgraceButton(post_key);
//Share click code below
viewHolder.Share.setOnClickListener(new View.OnClickListener() {
CallbackManager callbackManager;
ShareDialog shareDialog;
#Override
public void onClick(View v) {
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
shareDialog = new ShareDialog(MyPosts.this);
if (ShareDialog.canShow(ShareLinkContent.class)) {
ShareLinkContent content = new ShareLinkContent.Builder()
.setContentTitle(model.getTitle())
.setContentDescription(model.getDescription())
.setImageUrl(Uri.parse(model.getImage()))
.setContentUrl(Uri.parse("https://developers.facebook.com"))
.build();
shareDialog.show(content);
shareDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {
#Override
public void onSuccess(Sharer.Result result) {
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
}
}
});
//Share click code ends above
//Appriciate button on click event below
viewHolder.Appriciate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProcessAppriciate=true;
mDatabaseAppriciate.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessAppriciate) {
if (dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())) {
mDatabaseAppriciate.child(post_key).child(mAuth.getCurrentUser().getUid()).removeValue();
mProcessAppriciate = false;
}else {
mDatabaseAppriciate.child(post_key).child(mAuth.getCurrentUser().getUid()).setValue(mAuth.getCurrentUser().getDisplayName());
mProcessAppriciate = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
//Appriciate button click event CODE ENDS
//Disgrace Button Click Event Code Starts
viewHolder.Disgrace.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProcessDisgrace=true;
mDatabaseDisgrace.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mProcessDisgrace) {
if (dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())) {
mDatabaseDisgrace.child(post_key).child(mAuth.getCurrentUser().getUid()).removeValue();
mProcessDisgrace = false;
} else {
mDatabaseDisgrace.child(post_key).child(mAuth.getCurrentUser().getUid()).setValue(mAuth.getCurrentUser().getDisplayName());
mProcessDisgrace = false;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
//Disgrace Button Click code Ends
}
};
postList.setAdapter(firebaseRecyclerAdapter);
//test code
firebaseRecyclerAdapter.notifyDataSetChanged();
}
public static class PostViewHolder extends RecyclerView.ViewHolder{
View mView;
Button Appriciate;
Button Disgrace;
Button Share;
DatabaseReference mDatabaseAppriciate;
DatabaseReference mDatabaseDisgrace;
FirebaseAuth mAuth;
public PostViewHolder(View itemView) {
super(itemView);
mView=itemView;
Appriciate=(Button) mView.findViewById(R.id.appriciate);
Disgrace=(Button) mView.findViewById(R.id.disgraceful);
Share=(Button) mView.findViewById(R.id.share);
mDatabaseAppriciate=FirebaseDatabase.getInstance().getReference().child("Appriciate");
mDatabaseDisgrace=FirebaseDatabase.getInstance().getReference().child("Disgrace");
mAuth=FirebaseAuth.getInstance();
mDatabaseAppriciate.keepSynced(true);
mDatabaseDisgrace.keepSynced(true);
}
public void setAppriciateButton(final String post_key){
mDatabaseAppriciate.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())){
Appriciate.setBackgroundColor(Color.GRAY);
Appriciate.setText("Appriciated");
}else{
Appriciate.setBackgroundColor(Color.GREEN);
Appriciate.setText("APPRICIATE");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
//SET DISGRACE BUTTON CODE BELOW
public void setDisgraceButton(final String post_key){
mDatabaseDisgrace.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())){
Disgrace.setBackgroundColor(Color.GRAY);
Disgrace.setText("Disgraced");
}else{
Disgrace.setBackgroundColor(Color.RED);
Disgrace.setText("DISGRACE");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
//SET DISGRACE BUTTON CODE ENDS
//Setting the title to the AllActivity
public void setTitle(String title){
TextView postTitle=(TextView) mView.findViewById(R.id.allPostTitle);
postTitle.setText(title);
}
public void setDescription(String description){
TextView postDescription=(TextView) mView.findViewById(R.id.allPostDescription);
postDescription.setText(description);
}
//PROFILE NAME EXPERIMENT
public void setProfileName(String profilename){
TextView postName=(TextView) mView.findViewById(R.id.profileName);
postName.setText(profilename);
}
public void setImage(final Context context, final String image) {
final ImageView postImage=(ImageView) mView.findViewById(R.id.allPostImage);
with(context).load(image).networkPolicy(NetworkPolicy.OFFLINE).into(postImage, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(context).load(image).resize(500,700).into(postImage);
}
});
}
//THREADING EXPERIMENT CODE
}
}

Categories

Resources