How to pass values from one activity to another class - java

I need to pass a value either String to another class
From my activity, to a class that uses services
I have tried with an interface but it can not, you can only attach a fragment, and I can not do it with an attempt since it is a class that runs in the background
How could I do it?
the main activity
public class SettingsActivity extends AppCompatActivity {
private TriStateToggleButton mNotifications;
private ImageButton mButtonFinish;
private CardView mCardTermsPrivacy;
private CardView mCardLicenses;
private CardView mCardLogOut;
private CardView mCardDonations;
private FirebaseUser mUser;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window w = getWindow();
w.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
w.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.acitvity_settings);
mUser = FirebaseAuth.getInstance().getCurrentUser();
initPantalla();
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/RobotoLight.ttf")
.setFontAttrId(R.attr.fontPath)
.build()
);
}
private void initPantalla(){
mButtonFinish = (ImageButton) findViewById(R.id.imageButtonRegresaMeet);
mButtonFinish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
mNotifications = (TriStateToggleButton) findViewById(R.id.triStateToggleNotifications);
mCardTermsPrivacy = (CardView) findViewById(R.id.cardViewTemrsPrivacy);
mCardLicenses = (CardView) findViewById(R.id.cardViewLicenses);
mCardDonations = (CardView) findViewById(R.id.cardViewDonations);
mCardLogOut = (CardView) findViewById(R.id.cardViewLogOut);
mCardTermsPrivacy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TermsDialogs termsDialogs = new TermsDialogs();
termsDialogs.setCancelable(true);
termsDialogs.show(getSupportFragmentManager(), null);
}
});
mCardLicenses.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EasyLicensesDialog easyLicensesDialog = new EasyLicensesDialog(SettingsActivity.this);
easyLicensesDialog.setTitle("Licenses");
easyLicensesDialog.setCancelable(true);
easyLicensesDialog.show();
}
});
mCardLogOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
if (AccessToken.getCurrentAccessToken() != null) {
LoginManager.getInstance().logOut();
}
Intent serviceIntent = new Intent(SettingsActivity.this ,FirebaseBackgroundService.class);
SettingsActivity.this.stopService(serviceIntent);
Intent intent = new Intent(SettingsActivity.this, RegisterActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
});
mNotifications.setOnToggleChanged(new TriStateToggleButton.OnToggleChanged() {
#Override
public void onToggle(TriStateToggleButton.ToggleStatus toggleStatus, boolean b, int i) {
switch(toggleStatus){
case on:
break;
case off:
break;
}
}
});
}
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
}
the service class, i need to pass a string in this
public class FirebaseBackgroundService extends Service {
private FirebaseUser mUser;
private SharedPreferences preferences;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
FirebaseApp.initializeApp(getApplicationContext());
mUser = FirebaseAuth.getInstance().getCurrentUser();
if(mUser != null) {
FirebaseUtils.getCHATSOLICITUDRef(mUser.getUid()).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(final DataSnapshot dataSnapshot, final String s) {
postNotif();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
private void postNotif(){
Intent notificationIntent = new Intent(getApplicationContext(), UserActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Notification noti = new Notification.Builder(this)
.setContentTitle("Chat request")
.setContentText("You have pending chat requests")
.setSmallIcon(R.drawable.ic_dry_cleaning_with_mineral_spirits)
.setContentIntent(contentIntent)
.setSound(soundUri)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
noti.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, noti);
}
}

use intents link for developers android

Related

Firebase get Current User null in new activity after logged in user

After Successful log in my SignIn activity intent to BloodBank activity and the activity check if there any Currentuser or not.
In my case when it comes to BloodBank activity after log in, the method returning current user is null always
Is there any idea how I can resolve this issue?
Here is my SignIn Activity.java
public class SignIn extends AppCompatActivity {
Button signIn,forgetPass;
TextView backToSignUp,number,password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
signIn=findViewById(R.id.signInButtonId);
forgetPass=findViewById(R.id.forgetPassButtonId);
backToSignUp=findViewById(R.id.signUpBack);
number=findViewById(R.id.signInNumberId);
password=findViewById(R.id.signInPasswordId);
signIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String _phone = number.getText().toString().trim();
final String _password = password.getText().toString().trim();
if (_phone.isEmpty()) {
number.setError("Enter Your Phone Number");
number.requestFocus();
return;
}
if (_password.isEmpty()) {
password.setError("Enter a password");
password.requestFocus();
return;
}
DatabaseReference reference= FirebaseDatabase.getInstance().getReference("BloodBank_users");
Query checkUser=reference.orderByChild("phone").equalTo(_phone);
checkUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
number.setError(null);
number.setEnabled(true);
String passwordFromDB = snapshot.child(_phone).child("password").getValue(String.class);
if (passwordFromDB.equals(_password)) {
password.setError(null);
password.setEnabled(true);
Intent intent = new Intent(getApplicationContext(),BloodBankMain.class);
startActivity(intent);
finish();
} else {
password.setError("Wrong Password Or User Name");
password.requestFocus();
}
}
else {
number.setError("This Number Is Not Registered");
number.requestFocus();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
}
}
Here is my BloodBank.Java
public class BloodBank extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blood_bank);
firebaseAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user!=null){
Intent intent = new Intent(BloodBank.this, BloodBankMain.class);
startActivity(intent);
finish();
}
else{
Intent intent = new Intent(BloodBank.this,SignIn.class);
startActivity(intent);
finish();
}
}
};
}
#Override
protected void onStart() {
super.onStart();
firebaseAuth.addAuthStateListener(mAuthListener);
}
#Override
protected void onResume() {
super.onResume();
firebaseAuth.addAuthStateListener(mAuthListener);
}
#Override
protected void onStop() {
super.onStop();
firebaseAuth.removeAuthStateListener(mAuthListener);
}
}

Data is not showing after querying in firestore

public class ShowingParticularProducts extends AppCompatActivity {
FirebaseFirestore mFirebaseFireStore;
private FirestoreRecyclerAdapter<ProductModel, showingParticularProductAdapter.showingParticularProductViewHolder> adapter;
public RecyclerView mRecyclerView;
List<String> AllProductName=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_showing_particular_products);
mRecyclerView = findViewById(R.id.RecyclerViewParticularProducts);
mFirebaseFireStore = FirebaseFirestore.getInstance();
ImageView returnHome = findViewById(R.id.ImageViewHome);
ImageView Cart=findViewById(R.id.ImageViewCartParticularProducts);
String SearchText=getIntent().getStringExtra("SearchName");
loadAllProductName();
if(SearchText != null) {
List<String> suggest=new ArrayList<>();
for(String search:AllProductName) {
if (search.toLowerCase().contains(SearchText)) {
suggest.add(search.toLowerCase());
}
}
Query query1 = mFirebaseFireStore.collection("Products").whereIn("SearchID", Collections.singletonList(suggest));
FirestoreRecyclerOptions<ProductModel> options1 = new FirestoreRecyclerOptions.Builder<ProductModel>().setQuery(query1, ProductModel.class).build();
adapter = new showingParticularProductAdapter(options1);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(adapter);
}
returnHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ShowingParticularProducts.this, HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
});
Cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cartActivity=new Intent(ShowingParticularProducts.this,CartActivity.class);
startActivity(cartActivity);
}
});
}
private void loadAllProductName() {
mFirebaseFireStore=FirebaseFirestore.getInstance();
Query query2=mFirebaseFireStore.collection("Products");
query2.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful()){
for(QueryDocumentSnapshot queryDocumentSnapshot: Objects.requireNonNull(task.getResult())){
AllProductName.add(queryDocumentSnapshot.getString("Name"));
}
}
}
});
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
No data is showing in RecyclerView after query each data using loop with the field in firestore..First I have load all the name of product in a array list then I query whether each name contain the search text, if contain then show all the data acording to that in RecyclerView.I hope this is clear to everybody.

Activity has leaked window that was originally added logcat error

Please solve my error.I am unable to figure out.
When I click on submit button,my app crashes.Why?Let me know if you want any more input from my side.
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button btn;
EditText txt1, txt2,txt3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=findViewById(R.id.button);
txt1=findViewById(R.id.editTextTextPersonName);
txt2=findViewById(R.id.editTextTextEmailAddress2);
txt3=findViewById(R.id.editTextTextPassword);
SharedPreferences pref = getSharedPreferences("mypref", MODE_PRIVATE);
Boolean islogged=pref.getBoolean("key3",false);
if (islogged){
Intent i=new Intent(MainActivity.this,MainActivity2.class);
startActivity(i);
finish();
}
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = txt2.getText().toString();
String password = txt3.getText().toString();
Intent i=new Intent(MainActivity.this,MainActivity2.class);
startActivity(i);
SharedPreferences pref = getSharedPreferences("mypref", MODE_PRIVATE);
SharedPreferences.Editor ed = pref.edit();
ed.putString("key1", email);
ed.putString("key2", password);
ed.putBoolean("key3",true);
ed.apply();
}
});
}
}
MainActivity2.java
public class MainActivity2 extends AppCompatActivity {
Button btn;
EditText txt1, txt2;
CheckBox keeplog;
Boolean b=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
btn=findViewById(R.id.login);
txt1=findViewById(R.id.loginemail);
txt2=findViewById(R.id.loginpassword);
keeplog=findViewById(R.id.checkBox);
keeplog.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
b=isChecked;
}
});
SharedPreferences pref = getSharedPreferences("mypref", MODE_PRIVATE);
Boolean islogin=pref.getBoolean("key4",false);
if (islogin){
Intent i=new Intent(MainActivity2.this,HomeScreen.class);
startActivity(i);
finish();
}
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences pref = getSharedPreferences("mypref", MODE_PRIVATE);
String email = pref.getString("key1", null);
String password = pref.getString("key2", null);
String email2 = txt1.getText().toString();
String password2 = txt2.getText().toString();
SharedPreferences pref2 = getSharedPreferences("mypref", MODE_PRIVATE);
SharedPreferences.Editor ed = pref2.edit();
ed.putBoolean("key4",b);
ed.apply();
if (email.equals(email2) && password.equals(password2)) {
Intent i = new Intent(MainActivity2.this, HomeScreen.class);
startActivity(i);
finish();
}
}
});
HomeScreen.java
public class HomeScreen extends AppCompatActivity{
Button button1,button2;
EditText n;
ProgressDialog pd;
String Note;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
Toast.makeText(this, "Welcome Home", Toast.LENGTH_SHORT).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.id1) {
final AlertDialog dialogBuilder = new AlertDialog.Builder(this).create();
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.custom_dialog, null);
n = (EditText) dialogView.findViewById(R.id.edt_comment);
button1 = (Button) dialogView.findViewById(R.id.buttonSubmit);
button2 = (Button) dialogView.findViewById(R.id.buttonCancel);
dialogBuilder.setView(dialogView);
dialogBuilder.show();
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialogBuilder.dismiss();
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SAVETASK();
// dialogBuilder.dismiss();
}
});
} else if (item.getItemId() == R.id.id2) {
startActivity(new Intent(HomeScreen.this,MainActivity2.class));
}
return super.onOptionsItemSelected(item);
}
public void SAVETASK() {
Note = n.getText().toString();
//password = txt2.getText().toString();
class Savedata extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(HomeScreen.this);
pd.setTitle("Saving data");
pd.setMessage("Please Wailt");
pd.show();
}
#Override
protected Void doInBackground(Void... voids) {
Task task = new Task();
task.setNote(Note);
DatabaseClient.getInstance(getApplicationContext()).getAppDatabase().taskdao().insert(task);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pd.dismiss();
Toast.makeText(HomeScreen.this, "Data inserted", Toast.LENGTH_SHORT).show();
// Intent intent = new Intent(HomeScreen.this, MainActivity2.class);
// startActivity(intent);
}
}
Savedata savedata = new Savedata();
savedata.execute();
}
}
Task.java
#Entity
public class Task implements Serializable {
#PrimaryKey(autoGenerate = true)
private int id;
#ColumnInfo(name = "name")
private String Note;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNote() {
return Note;
}
public void setNote(String note) {
Note = note;
}
}
TaskDao.java
#Dao
public interface TaskDao {
#Query("select * from task")
List<Task> getalldata();
#Insert
void insert(Task task);
#Update
void update(Task task);
#Delete
void Delete(Task task);
}
AppDatabase.java
public abstract class AppDatabase extends RoomDatabase {
public abstract TaskDao taskdao();
}
DatabaseClient.java
public class DatabaseClient {
private Context context;
private static DatabaseClient mInstance;
private AppDatabase appDatabase;
private DatabaseClient(Context mctx)
{
this.context=mctx;
appDatabase= Room.databaseBuilder(mctx,AppDatabase.class,"MYTODO").build();
}
public static synchronized DatabaseClient getInstance(Context context)
{
if(mInstance==null)
{
mInstance=new DatabaseClient(context);
}
return mInstance;
}
public AppDatabase getAppDatabase()
{
return appDatabase;
}
}
Logcat error:
com.example.sharedprefdemo E/WindowManager: android.view.WindowLeaked: Activity com.example.sharedprefdemo.HomeScreen has leaked window DecorView#d93e50e[Saving data] that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:765)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:429)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:95)
at android.app.Dialog.show(Dialog.java:473)
at com.example.sharedprefdemo.HomeScreen$1Savedata.onPreExecute(HomeScreen.java:95)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:708)
at android.os.AsyncTask.execute(AsyncTask.java:655)
at com.example.sharedprefdemo.HomeScreen.SAVETASK(HomeScreen.java:117)
at com.example.sharedprefdemo.HomeScreen$2.onClick(HomeScreen.java:70)
at android.view.View.performClick(View.java:7870)
at android.widget.TextView.performClick(TextView.java:14970)
at android.view.View.performClickInternal(View.java:7839)
at android.view.View.access$3600(View.java:886)
at android.view.View$PerformClick.run(View.java:29363)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7814)
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:1068)
So when I click on submit button,my app crashes automatically.I dont know what is the reason.
Before showing dialog
if(dialog != null && dialog.isShowing()) {
dialog.dismiss();//or cancel()
}
Try moving the dialog and its initialization from asyncthread
HomeScreen has leaked window DecorView#d93e50e[Saving data] that was originally added here
answer to this error

Call adapter.notifyItemChanged(position); working so weird

I have a list that I get from firebase, this list is about posts and what I need is when user like it or unlike it, the list updated through adapter. as I used recyclerview and adapter to show my data after receiving it from firebase. Actually, everything works so fine with me but just this issue when user like or unlike the post it goes crazy. I tried to make a toast to make sure that I'm working with the same position as I expected and it proved me right.
the photo of the post appears and disappears by clicking like button like the vides shows and it does not updating the data in a proper way like it mess with the number of likes
You can find my code below with a video to illustrate the problem I am facing.
I hope somebody can help me out.
private void read_posts() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
reference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
//post_models.clear();
Post_Model post_model = dataSnapshot.getValue(Post_Model.class);
post_models.add(post_model);
post_adapter = new Post_Adapter(post_models, getContext());
recyclerviewNewsfeed.setAdapter(post_adapter);
progressBar.setVisibility(View.GONE);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Post_Model post_model = dataSnapshot.getValue(Post_Model.class);
for (int i=0;i<post_models.size();i++){
if(post_models.get(i).getId().equals(post_model.getId())){
post_models.set(i,post_model);
post_adapter.notifyItemChanged(i);
break;
}
}
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
It's my post adapter
public class Post_Adapter extends RecyclerView.Adapter<Post_Adapter.Viewholder> {
private Context context;
private List<Post_Model> post_models;
FirebaseUser firebaseUser;
List<Like_Model> like_modelList, likeblue_modelList;
View_Photos_Adapter view_Photos_adapter;
boolean userlikeit;
public static int positionn=-1;
public Post_Adapter(List<Post_Model> post_models, Context context) {
this.context = context;
this.post_models = post_models;
}
#NonNull
#Override
public Viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.post_item, parent, false);
return new Viewholder(view);
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull final Viewholder holder, final int position) {
final Post_Model post_model = post_models.get(position);
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference referencee = FirebaseDatabase.getInstance().getReference("Posts").child(post_model.getId());
referencee.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//Toast.makeText(CommentActivity.this, post_id+"", Toast.LENGTH_SHORT).show();
Post_Model post_modell = dataSnapshot.getValue(Post_Model.class);
// Toast.makeText(CommentActivity.this, post_id+"", Toast.LENGTH_SHORT).show();
if (post_modell.getLikeModels() != null) {
for (int i = 0; i < post_modell.getLikeModels().size(); i++) {
if (post_modell.getLikeModels().get(i).getUserid().equals(firebaseUser.getUid())) {
userlikeit = true;
break;
} else {
userlikeit = false;
}
}
} else {
userlikeit = false;
}
//snapshot.getRef().removeValue();
// Toast.makeText(context, userlikeit+"58", Toast.LENGTH_SHORT).show();
//Toast.makeText(CommentActivity.this, comment_models.size()+"", Toast.LENGTH_SHORT).show();
if (userlikeit) {
holder.likebluebtn.setVisibility(View.VISIBLE);
holder.likebtn.setVisibility(View.GONE);
} else {
holder.likebtn.setVisibility(View.VISIBLE);
holder.likebluebtn.setVisibility(View.GONE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
if (post_model.getUserid().equals(firebaseUser.getUid())) {
holder.editbtn.setVisibility(View.VISIBLE);
holder.deletebtn.setVisibility(View.VISIBLE);
} else {
holder.editbtn.setVisibility(View.GONE);
holder.deletebtn.setVisibility(View.GONE);
}
holder.editbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.postTextView.setVisibility(View.GONE);
holder.postEditText.setVisibility(View.VISIBLE);
holder.postEditText.setText(post_model.getPost());
holder.editbtn.setVisibility(View.GONE);
holder.savebtn.setVisibility(View.VISIBLE);
}
});
holder.savebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Post_Model post_modell = new Post_Model(post_model.getId(), post_model.getUserid()
, holder.postEditText.getText().toString(), post_model.getTime()
, post_model.getCommentModels(), post_model.getPostphotos(), post_model.getLikeModels());
FirebaseDatabase.getInstance().getReference("Posts")
.child(post_model.getId())
.setValue(post_modell);
holder.postTextView.setVisibility(View.VISIBLE);
holder.postEditText.setVisibility(View.GONE);
holder.editbtn.setVisibility(View.VISIBLE);
holder.savebtn.setVisibility(View.GONE);
Toast.makeText(context, "Post has been edited successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, NewsfeedActivity.class);
context.startActivity(intent);
((Activity) context).overridePendingTransition(R.anim.slide_in_right, R.anim.slide_in_left);
((Activity) context).finish();
}
});
holder.deletebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new AlertDialog.Builder(context)
.setTitle("Delete Post")
.setMessage("Are you sure you want to delete this post?")
// Specifying a listener allows you to take an action before dismissing the dialog.
// The dialog is automatically dismissed when a dialog button is clicked.
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
final DatabaseReference referencee = FirebaseDatabase.getInstance().getReference("Posts")
.child(post_model.getId());
referencee.removeValue();
Toast.makeText(context, "Post deleted successfully", Toast.LENGTH_LONG).show();
Intent intent = new Intent(context, NewsfeedActivity.class);
context.startActivity(intent);
((Activity) context).overridePendingTransition(R.anim.slide_in_right, R.anim.slide_in_left);
((Activity) context).finish();
}
})
// A null listener allows the button to dismiss the dialog and take no further action.
.setNegativeButton(android.R.string.no, null)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
});
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
like_modelList = new ArrayList<>();
likeblue_modelList = new ArrayList<>();
//Toast.makeText(context, read_likes(post_model.getId())+"", Toast.LENGTH_SHORT).show();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
// Toast.makeText(Create_Coworking_SpaceActivity.this, "111111111", Toast.LENGTH_LONG).show();
if (user.getId().equals(post_model.getUserid())) {
if (user.getImageURL().equals("default")) {
holder.userImage.setImageResource(R.drawable.ic_imgprofile);
} else {
Glide.with(holder.itemView).load(user.getImageURL()).into( holder.userImage);
}
holder.username.setText(user.getUsername());
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
if (post_model.getPostphotos() == null) {
holder.postPhotosRC.setVisibility(View.GONE);
} else {
holder.postPhotosRC.setHasFixedSize(true);
holder.postPhotosRC.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
view_Photos_adapter = new View_Photos_Adapter(post_model.getPostphotos(), context);
holder.postPhotosRC.setAdapter(view_Photos_adapter);
}
holder.postTextView.setText(post_model.getPost());
holder.posttimeTextView.setText(post_model.getTime());
holder.commentbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, CommentActivity.class);
intent.putExtra("post_id", post_model.getId());
context.startActivity(intent);
((Activity) context).overridePendingTransition(R.anim.slide_in_right, R.anim.slide_in_left);
}
});
if (post_model.getCommentModels() != null) {
holder.numofcommentsEditText.setText(post_model.getCommentModels().size() + "");
holder.numofcommentsTextView.setText(post_model.getCommentModels().size() + "");
}
final int[] li = {0};
holder.likebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
like(post_model.getId());
// Post_Adapter.this.notifyItemChanged(position);
positionn=position;
}
});
holder.likebluebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context, userlikeit+"5", Toast.LENGTH_SHORT).show();
unlike(post_model.getId());
// Post_Adapter.this.notifyItemChanged(position);
positionn=position;
}
});
if (post_model.getLikeModels() != null) {
holder.numoflikesEditText.setText(post_model.getLikeModels().size() + "");
holder.numoflikesTextView.setText(post_model.getLikeModels().size() + "");
}
holder.likesTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, LikeActivity.class);
intent.putExtra("post_id", post_model.getId());
context.startActivity(intent);
((Activity) context).overridePendingTransition(R.anim.slide_in_right, R.anim.slide_in_left);
}
});
holder.commentsTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, CommentActivity.class);
intent.putExtra("post_id", post_model.getId());
context.startActivity(intent);
((Activity)
context).overridePendingTransition(R.anim.slide_in_right,
R.anim.slide_in_left);
}
});
}
#Override
public int getItemCount() {
return post_models == null ? 0 : post_models.size();
}

Multiple startActivityForResult()

I need to call this function twice in my application pointing to two different activities. I have a unique request code for each call, however my app seems to crash everytime it launches the second activity.
Here is my code (only relevant parts):
MainActivity:
//Request Info vars
static final int GET_DETAILS = 1;
static final int EDIT_DETAILS = 2;
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
public void onMapClick(LatLng latLng) {
lat = latLng.latitude;
lon = latLng.longitude;
startActivityForResult(new Intent(MapsActivity.this,NewMarkerActivity.class), GET_DETAILS);
}
});
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
current_marker = marker;
startActivityForResult(new Intent(MapsActivity.this,EditMarkerActivity.class), EDIT_DETAILS);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == GET_DETAILS) {
if (resultCode == RESULT_OK) {
String marker_title=data.getStringExtra("title");
String marker_snippet = data.getStringExtra("snippet");
addMarker(lat, lon, marker_title, marker_snippet);
mMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(lat, lon)));
}
} if (requestCode == EDIT_DETAILS) {
if (resultCode == RESULT_OK) {
String marker_title=data.getStringExtra("title");
String marker_snippet = data.getStringExtra("snippet");
current_marker.setTitle(marker_title);
current_marker.setSnippet(marker_snippet);
}
}
}
EditMarkerActivity:
public class EditMarkerActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_marker_activity);
Button save_btn = (Button)findViewById(R.id.btn_save);
save_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText editName = (EditText)findViewById(R.id.editName);
String marker_title = editName.getText().toString();
EditText editSnippet = (EditText)findViewById(R.id.editSnippet);
String marker_snippet = editSnippet.getText().toString();
Intent _result = new Intent();
_result.putExtra("title", marker_title);
_result.putExtra("snippet", marker_snippet);
setResult(Activity.RESULT_OK, _result);
finish();
}
});
}
}
NewMarkerActivity:
public class NewMarkerActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_marker_activity);
Button save_btn = (Button)findViewById(R.id.btn_save);
save_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText editName = (EditText)findViewById(R.id.editName);
String marker_title = editName.getText().toString();
EditText editSnippet = (EditText)findViewById(R.id.editSnippet);
String marker_snippet = editSnippet.getText().toString();
Intent _result = new Intent();
_result.putExtra("title", marker_title);
_result.putExtra("snippet", marker_snippet);
setResult(Activity.RESULT_OK, _result);
finish();
}
});
}
}
Any obvious issues? Help or insight to this problem will be greatly appreciated :)
Here is my output from Logcat:
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.geekybrackets.virtualtourguide/com.geekybrackets.virtualtourguide.EditMarkerActivity}; have you declared this activity in your AndroidManifest.xml?
Turns out the issue was that I hadn't defined the activity in the manifest file.
Dear old me, now i know to check my errors !
Thanks again guys, case closed.

Categories