package e.starf.project;
import android.content.Context;
import android.content.Intent;
import android.media.Image;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.module.AppGlideModule;
import com.bumptech.glide.Glide;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class MainActivity extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
private RecyclerView postList;
private Toolbar toolbar;
private ImageButton AddNewPostButton;
private FirebaseAuth firebaseAuth;
private DatabaseReference UsersRef, PostsRef, LikesRef;
private StorageReference mStorageRef;
String currentUserID;
Boolean LikeChecker = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");
LikesRef = FirebaseDatabase.getInstance().getReference().child("Likes");
UsersRef.keepSynced(true);
PostsRef.keepSynced(true);
LikesRef.keepSynced(true);
mStorageRef = FirebaseStorage.getInstance().getReference();
toolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Home");
AddNewPostButton = (ImageButton) findViewById(R.id.add_new_post);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayout,
R.string.drawer_open, R.string.drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
postList = (RecyclerView) findViewById(R.id.all_users_post_list);
postList.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
postList.setLayoutManager(linearLayoutManager);
View navView = navigationView.inflateHeaderView(R.layout.navigration_header);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
UserMenuSelector(item);
return false;
}
});
AddNewPostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SendUserToPostActivity();
}
});
DisplayAllUsersPosts();
}
private void DisplayAllUsersPosts() {
final FirebaseRecyclerOptions < Posts options = new FirebaseRecyclerOptions.Builder < Posts().setQuery(PostsRef,
Posts.class).build();
FirebaseRecyclerAdapter < Posts, PostsViewHolder firebaseRecyclerAdapter = new FirebaseRecyclerAdapter < Posts,
PostsViewHolder(options) {
#NonNull
#Override
public PostsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.all_posts_layout,
viewGroup, false);
return new PostsViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull final PostsViewHolder holder, int position, #NonNull final Posts model) {
final String PostKey = getRef(position).getKey();
holder.setName(model.getName());
holder.setTime(model.getTime());
holder.setDate(model.getDate());
holder.setDescription(model.getDescription());
holder.setPostimage(getApplicationContext(), model.getPostimage());
holder.setLikeButtonStatus(PostKey);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent clickPostIntent = new Intent(MainActivity.this, ClickPostActivity.class);
clickPostIntent.putExtra("PostKey", PostKey);
startActivity(clickPostIntent);
}
});
holder.CommentPostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent clickPostIntent = new Intent(MainActivity.this, CommentsActivity.class);
clickPostIntent.putExtra("PostKey", PostKey);
startActivity(clickPostIntent);
}
});
holder.LikePostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LikeChecker = true;
if (LikeChecker) {
LikesRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (LikeChecker.equals(true)) {
if (dataSnapshot.child(PostKey).hasChild(currentUserID)) {
LikesRef.child(PostKey).child(currentUserID).removeValue();
LikeChecker = false;
} else {
LikesRef.child(PostKey).child(currentUserID).setValue(true);
LikeChecker = false;
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
});
}
};
postList.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.startListening();
}
public static class PostsViewHolder extends RecyclerView.ViewHolder {
View mView;
ImageButton LikePostButton, CommentPostButton;
TextView DisplayNoOfLikes;
int countLikes;
String currentUserID;
DatabaseReference LikesRef;
public PostsViewHolder(#NonNull View itemView) {
super(itemView);
mView = itemView;
LikePostButton = (ImageButton) mView.findViewById(R.id.like_button);
CommentPostButton = (ImageButton) mView.findViewById(R.id.comment_button);
DisplayNoOfLikes = (TextView) mView.findViewById(R.id.display_no_of_likes);
LikesRef = FirebaseDatabase.getInstance().getReference().child("Likes");
currentUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
}
public void setLikeButtonStatus(final String PostKey) {
LikesRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child(PostKey).hasChild(currentUserID)) {
countLikes = (int) dataSnapshot.child(PostKey).getChildrenCount();
LikePostButton.setImageResource(R.drawable.like);
DisplayNoOfLikes.setText(Integer.toString(countLikes) + (" Likes"));
} else {
countLikes = (int) dataSnapshot.child(PostKey).getChildrenCount();
LikePostButton.setImageResource(R.drawable.dislike);
DisplayNoOfLikes.setText(Integer.toString(countLikes) + (" Likes"));
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void setName(String name) {
TextView username = (TextView) mView.findViewById(R.id.post_user_name);
username.setText(name);
}
public void setTime(String time) {
TextView PostTime = (TextView) mView.findViewById(R.id.post_time);
PostTime.setText(" " + time);
}
public void setDate(String date) {
TextView PostDate = (TextView) mView.findViewById(R.id.post_date);
PostDate.setText(" " + date);
}
public void setDescription(String description) {
TextView PostDescription = (TextView) mView.findViewById(R.id.post_question);
PostDescription.setText(description);
}
public void setPostimage(Context ctx, String postimage) {
ImageView PostImage = (ImageView) mView.findViewById(R.id.post_image);
Picasso.get().load(postimage).into(PostImage);
// Glide.with(ctx).load(postimage).into(PostImage);
}
}
private void SendUserToPostActivity() {
Intent addNewPostIntent = new Intent(MainActivity.this, PostActivity.class);
startActivity(addNewPostIntent);
}
protected void onStart() {
super.onStart();
FirebaseUser currentUser = firebaseAuth.getCurrentUser();
if (currentUser == null) {
SendUserToLoginActivity();
} else {
CheckUserExistence();
}
}
private void CheckUserExistence() {
final String current_user_id = firebaseAuth.getCurrentUser().getUid();
UsersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(current_user_id)) {
SendUserToSetupActivity();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void SendUserToSetupActivity() {
Intent setupIntent = new Intent(MainActivity.this, SetupActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(setupIntent);
finish();
}
private void SendUserToLoginActivity() {
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
private void SendUserToProfileActivity() {
Intent profileIntent = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(profileIntent);
}
private void SendUserToAboutUsActivity() {
Intent AboutUsIntent = new Intent(MainActivity.this, AboutUs.class);
startActivity(AboutUsIntent);
}
private void SendUserToContactUsActivity() {
Intent AboutUsIntent = new Intent(MainActivity.this, ContactUs.class);
startActivity(AboutUsIntent);
}
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void UserMenuSelector(MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_post:
SendUserToPostActivity();
break;
case R.id.nav_menu1:
Toast.makeText(this, "Home", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_menu2:
Toast.makeText(this, "Discussion FOrum", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_menu3:
SendUserToProfileActivity();
break;
case R.id.nav_menu4:
SendUserToAboutUsActivity();
break;
case R.id.nav_menu5:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "PICT Placement.\n Forum to create awareness...\nLink:
https: //github.com/pragyagupta1898");
sendIntent.setType("text/plain"); startActivity(sendIntent); Toast.makeText(this, "Share", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_contact:
SendUserToContactUsActivity();
break;
case R.id.nav_logout:
firebaseAuth.signOut(); SendUserToLoginActivity();
break;
}
}
}
The error is here:
if(dataSnapshot.child(PostKey).hasChild(currentUserID))
It says:
Argument 'PostKey' might be null less... (Ctrl+F1)
This inspection analyzes method control and data flow to report possible conditions that are always true or false, expressions whose value is statically proven to be constant, and situations that can lead to nullability contract violations.
Variables, method parameters and return values marked as #Nullable or #NotNull are treated as nullable (or not-null, respectively) and used during the analysis to check nullability contracts, e.g. report NullPointerException (NPE) errors that might be produced.
More complex contracts can be defined using #Contract annotation, for example:
#Contract(", null - null") — method returns null if its second argument is null #Contract(", null - null; _, !null - !null") — method returns null if its second argument is null and not-null otherwise #Contract("true - fail") — a typical assertFalse method which throws an exception if true is passed to it
The inspection can be configured to use custom #Nullable
#NotNull annotations (by default the ones from annotations.jar will be used)
How to resolve it?
That's not an error, it's a warning.
Since it doesn't seem that you read the warning you quoted, I'll paraphrase:
The DataSnapshot.child() method has a #Nullable flag, meaning it's possible that it will return null. Since you are calling something directly on the result of that method, Android Studio is simply telling you that, since child() can be null, running hasChild() on it might lead to a NullPointerException.
Either check the null state or ignore it.
try something like this.
if((PostKey != null) && dataSnapshot.child(PostKey).hasChild(currentUserID))
You can also write it so that you handle the null case
if (PostKey == null) //do somthing
else if (dataSnapshot.child(PostKey).hasChild(currentUserID)) //do something
else //do something
If you debug your app at this warning you will found that the mUserID = null,
so you just need to inti it:
mUserID = mAuth.getCurrentUser().getUid();
Related
This question already has answers here:
Android - Client-side sorting with FirebaseRecyclerAdapter
(1 answer)
FirebaseRecyclerPagingAdapter - sort list by date
(1 answer)
Cannot retrieve data in ascending order
(2 answers)
Firebase Data Desc Sorting in Android
(19 answers)
How to arrange firebase database data in ascending or descending order?
(2 answers)
Closed 8 months ago.
As now i am working on a chat application, here i have a problem that how can i display my last recent chat on the top of the recyclerview in ChatlistFragment,
for example if i had recently sent my last message to any user they have to displayed at the top of my recyclerview, here is my code
package com.micoder.whatsappclone;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class ChatsFragment extends Fragment {
private View PrivateChatsView;
private RecyclerView chatsList;
private DatabaseReference ChatsRef, UsersRef;
private FirebaseAuth mAuth;
private String currentUserID;
FloatingActionMenu fabMenu;
FloatingActionButton fabSettings, fabShare, fabContactDev;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
PrivateChatsView = inflater.inflate(R.layout.fragment_chats, container, false);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
ChatsRef = FirebaseDatabase.getInstance().getReference().child("Messages").child(currentUserID);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
chatsList = (RecyclerView) PrivateChatsView.findViewById(R.id.chats_list);
chatsList.setLayoutManager(new LinearLayoutManager(getContext()));
fabOptions();
return PrivateChatsView;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerOptions<Contacts> options =
new FirebaseRecyclerOptions.Builder<Contacts>()
.setQuery(ChatsRef, Contacts.class)
.build();
FirebaseRecyclerAdapter<Contacts, ChatsViewHolder> adapter =
new FirebaseRecyclerAdapter<Contacts, ChatsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull ChatsViewHolder holder, int position, #NonNull Contacts model) {
final String usersIDs = getRef(position).getKey();
final String[] retImage = {"default_image"};
UsersRef.child(usersIDs).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.child("userState").hasChild("state")) {
String state = dataSnapshot.child("userState").child("state").getValue().toString();
if (state.equals("online")) {
holder.onlineIcon.setVisibility(View.VISIBLE);
}
else if (state.equals("offline")) {
holder.onlineIcon.setVisibility(View.INVISIBLE);
}
}
else {
holder.onlineIcon.setVisibility(View.INVISIBLE);
}
if (dataSnapshot.exists()) {
if (dataSnapshot.hasChild("image")) {
retImage[0] = dataSnapshot.child("image").getValue().toString();
Picasso.get().load(retImage[0]).placeholder(R.drawable.profile_image).into(holder.profileImage);
}
final String retName = dataSnapshot.child("name").getValue().toString();
holder.userName.setText(retName);
if (dataSnapshot.child("userState").hasChild("state")) {
String state = dataSnapshot.child("userState").child("state").getValue().toString();
String date = dataSnapshot.child("userState").child("date").getValue().toString();
String time = dataSnapshot.child("userState").child("time").getValue().toString();
if (state.equals("online")) {
holder.userStatus.setText("online");
}
else if (state.equals("offline")) {
holder.userStatus.setText("Last Seen: " + date + " " + time);
}
}
else {
holder.userStatus.setText("offline");
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent chatIntent = new Intent(getContext(), ChatActivity.class);
chatIntent.putExtra("visit_user_id", usersIDs);
chatIntent.putExtra("visit_user_name", retName);
chatIntent.putExtra("visit_image", retImage[0]);
startActivity(chatIntent);
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#NonNull
#Override
public ChatsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.users_display_chats_layout, viewGroup, false);
return new ChatsViewHolder(view);
}
};
chatsList.setAdapter(adapter);
adapter.startListening();
}
public static class ChatsViewHolder extends RecyclerView.ViewHolder {
CircleImageView profileImage;
TextView userName, userStatus;
ImageView onlineIcon;
public ChatsViewHolder(#NonNull View itemView) {
super(itemView);
profileImage = itemView.findViewById(R.id.users_profile_image);
userName = itemView.findViewById(R.id.user_profile_name);
userStatus = itemView.findViewById(R.id.user_status);
onlineIcon = itemView.findViewById(R.id.user_online_status);
}
}
public void fabOptions() {
//FAB
fabMenu=PrivateChatsView.findViewById(R.id.fabMenu);
fabSettings=PrivateChatsView.findViewById(R.id.fabSettings);
fabContactDev=PrivateChatsView.findViewById(R.id.fabContactDev);
fabShare=PrivateChatsView.findViewById(R.id.fabShare);
fabShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "My application name");
String shareMessage= "\nLet me recommend you this application\n\n";
shareMessage = shareMessage + "https://play.google.com/store/apps/developer?id=MI_CODER"+"\n\n";
shareIntent.putExtra(Intent.EXTRA_TEXT, shareMessage);
startActivity(Intent.createChooser(shareIntent, "choose one"));
} catch(Exception e) {
//e.toString();
}
fabMenu.close(true);
}
});
fabSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Settings", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getActivity(),SettingsActivity.class));
fabMenu.close(true);
}
});
fabContactDev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(),"Loading...",Toast.LENGTH_SHORT).show();
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://micoder-dev.github.io/Resume-Page/"));
startActivity(browserIntent);
fabMenu.close(true);
}
});
}
}
if you need to refer my complete source code you can get here => https://github.com/Micoder-dev/ChatApp-FE-UI.git
I think this will help you to make it easier to get a solution.
This question already has answers here:
Firebase No properties to serialize found on class
(12 answers)
Firebase release apk not loading data
(3 answers)
Firebase AndroidChat release build error
(3 answers)
Closed 2 years ago.
On my android studio debug theres nothing problem, but when i publish the app to playstore my app was close after splashscreen. my apps using firebase, and i have to added SHA-1 from playstore to my firebase project. but still cant crash :
this error i got from play console :
com.google.firebase.database.DatabaseException:
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.<init> (CustomClassMapper.java:11)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.loadOrCreateBeanMapperForClass (CustomClassMapper.java)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean (CustomClassMapper.java:4)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass (CustomClassMapper.java:4)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass (CustomClassMapper.java:8)
at com.google.firebase.database.DataSnapshot.getValue (DataSnapshot.java:8)
at com.kepulcorporation.kepul.HomeFragment$10.onDataChange (HomeFragment.java:8)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent (ValueEventRegistration.java:2)
at com.google.firebase.database.core.view.DataEvent.fire (DataEvent.java)
at com.google.firebase.database.core.view.EventRaiser$1.run (EventRaiser.java:6)
at android.os.Handler.handleCallback (Handler.java:751)
at android.os.Handler.dispatchMessage (Handler.java:95)
at android.os.Looper.loop (Looper.java:154)
at android.app.ActivityThread.main (ActivityThread.java:6121)
at java.lang.reflect.Method.invoke (Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:779)
this is my main activity :
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Registry;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.module.AppGlideModule;
import com.firebase.ui.storage.images.FirebaseImageLoader;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.storage.StorageReference;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private ActionBar actionBar;
private NestedScrollView nested_scroll_view;
private BottomSheetBehavior mBehavior;
private BottomSheetDialog mBottomSheetDialog;
private View bottom_sheet;
private HorizontalScrollView horizontalScrollView;
private Fragment fragment;
private Fragment fragmenthome;
private SessionManager sessionManager;
RelativeLayout toolbar;
LinearLayout content;
NestedScrollView scrolllayout;
ImageView home_icon, transaksi_icon, bantuan_icon, akun_icon;
TextView home_text, transaksi_text, bantuan_text, akun_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
content = findViewById(R.id.list_category_item_dashboard);
scrolllayout = findViewById(R.id.nested_scroll_view);
//Set Theme
Tools.setSystemBarColor(this, R.color.colorPrimary);
sessionManager = new SessionManager(this);
sessionManager.checkLogin(this);
home_icon = findViewById(R.id.home_icon);
transaksi_icon = findViewById(R.id.transaksi_icon);
bantuan_icon = findViewById(R.id.bantuan_icon);
akun_icon = findViewById(R.id.akun_icon);
home_text = findViewById(R.id.home_text);
transaksi_text = findViewById(R.id.transaksi_text);
bantuan_text = findViewById(R.id.bantuan_text);
akun_text = findViewById(R.id.akun_text);
FirebaseMessaging.getInstance().getToken()
.addOnCompleteListener(new OnCompleteListener<String>() {
#Override
public void onComplete(#NonNull Task<String> task) {
if (!task.isSuccessful()) {
// Toast.makeText(MainActivity.this, "Fetching FCM registration token failed", Toast.LENGTH_SHORT).show();
return;
}
// Get new FCM registration token
String token = task.getResult();
if(sessionManager.isLoggin())
{
save_fcm(token);
}
}
});
initComponent();
}
public void save_fcm(String token){
HashMap<String, String> user;
sessionManager = new SessionManager(MainActivity.this);
user = sessionManager.getUserDetail();
String email = user.get("EMAIL");
String convertemail = email.replaceAll("\\.", "_");
FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference tableuser = database.getReference("Users");
tableuser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String email = user.get("EMAIL");
String convertemail = email.replaceAll("\\.", "_");
Users users = snapshot.child(convertemail).getValue(Users.class);
Map<String, Object> updates = new HashMap<String,Object>();
updates.put("address", users.getAddress());
updates.put("email", email);
updates.put("name", users.getName());
updates.put("password", users.getPassword());
updates.put("phone", users.getPhone());
updates.put("photo_profile_path", users.getPhoto_profile_path());
updates.put("role_id", users.getRole_id());
updates.put("point", users.getPoint());
updates.put("token", token);
updates.put("promosipush", users.getPromosipush());
updates.put("promosiemail", users.getPromosiemail());
updates.put("statuspush", users.getStatuspush());
updates.put("statusemail", users.getStatusemail());
tableuser.child(convertemail).setValue(updates);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void initComponent() {
nested_scroll_view = (NestedScrollView) findViewById(R.id.nested_scroll_view);
fragment = new HomeFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.colorPrimary));
home_text.setTextColor(this.getResources().getColor(R.color.colorPrimary));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
} else {
Toast.makeText(getApplicationContext(), item.getTitle(), Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
public void toHome(View view) {
ViewAnimation.fadeOutIn(nested_scroll_view);
if (sessionManager.isLoggin()){
fragment = new HomeFragment();
}
else {
fragment = new HomeFragment();
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.colorPrimary));
home_text.setTextColor(this.getResources().getColor(R.color.colorPrimary));
transaksi_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
transaksi_text.setTextColor(this.getResources().getColor(R.color.text));
bantuan_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
bantuan_text.setTextColor(this.getResources().getColor(R.color.text));
akun_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
akun_text.setTextColor(this.getResources().getColor(R.color.text));
}
public void toTransaksi(View view) {
ViewAnimation.fadeOutIn(nested_scroll_view);
if (sessionManager.isLoggin()){
fragment = new TransaksiloginFragment();
}
else {
fragment = new TransaksiFragment();
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
home_text.setTextColor(this.getResources().getColor(R.color.text));
transaksi_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.colorPrimary));
transaksi_text.setTextColor(this.getResources().getColor(R.color.colorPrimary));
bantuan_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
bantuan_text.setTextColor(this.getResources().getColor(R.color.text));
akun_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
akun_text.setTextColor(this.getResources().getColor(R.color.text));
}
public void toBantuan(View view){
ViewAnimation.fadeOutIn(nested_scroll_view);
if (sessionManager.isLoggin()){
fragment = new BantuanFragment();
}
else {
fragment = new BantuanFragment();
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
home_text.setTextColor(this.getResources().getColor(R.color.text));
transaksi_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
transaksi_text.setTextColor(this.getResources().getColor(R.color.text));
bantuan_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.colorPrimary));
bantuan_text.setTextColor(this.getResources().getColor(R.color.colorPrimary));
akun_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
akun_text.setTextColor(this.getResources().getColor(R.color.text));
}
public void toAkun(View view){
ViewAnimation.fadeOutIn(nested_scroll_view);
if (sessionManager.isLoggin()){
fragment = new AkunLoginFragment();
}
else {
fragment = new AkunFragment();
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
home_text.setTextColor(this.getResources().getColor(R.color.text));
transaksi_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
transaksi_text.setTextColor(this.getResources().getColor(R.color.text));
bantuan_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
bantuan_text.setTextColor(this.getResources().getColor(R.color.text));
akun_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.colorPrimary));
akun_text.setTextColor(this.getResources().getColor(R.color.colorPrimary));
}
public void toSell(View view) {
ViewAnimation.fadeOutIn(nested_scroll_view);
if (sessionManager.isLoggin()){
startActivity(new Intent(MainActivity.this, JualsampahActivity.class));
}
else {
fragment = new JualFragment();
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, fragment,
fragment.getClass().getSimpleName()).commit();
home_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
home_text.setTextColor(this.getResources().getColor(R.color.text));
transaksi_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
transaksi_text.setTextColor(this.getResources().getColor(R.color.text));
bantuan_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
bantuan_text.setTextColor(this.getResources().getColor(R.color.text));
akun_icon.setBackgroundTintList(this.getResources().getColorStateList(R.color.text));
akun_text.setTextColor(this.getResources().getColor(R.color.text));
}
}
and this my HomeFragment :
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.media.Image;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.github.islamkhsh.CardSliderViewPager;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import org.w3c.dom.Text;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
import ru.tinkoff.scrollingpagerindicator.ScrollingPagerIndicator;
public class HomeFragment extends Fragment {
CardSliderViewPager cardSliderViewPager;
private List<Category>listData;
private List<Produk>listData1;
private List<SliderData>sliderData;
private RecyclerView rv;
private CategoryAdapter adapter;
private ProdukAdapter adapter1;
private SliderAdapter sliderAdapter;
private RecyclerView recyclerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View root = inflater.inflate(R.layout.fragment_home, container, false);
cardSliderViewPager = root.findViewById(R.id.viewPager);
recyclerView = root.findViewById(R.id.product_recyclerview);
rv = root.findViewById(R.id.category_recyclerview);
rv.setHasFixedSize(true);
rv.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
listData=new ArrayList<>();
listData1 = new ArrayList<>();
sliderData = new ArrayList<>();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference table = database.getReference("Category");
table.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(isAdded())
{
listData.clear();
for (DataSnapshot npsnapshot : snapshot.getChildren()){
Category l = npsnapshot.getValue(Category.class);
listData.add(l);
}
adapter=new CategoryAdapter(listData);
rv.setAdapter(adapter);
ScrollingPagerIndicator recyclerIndicator = root.findViewById(R.id.indicator2);
recyclerIndicator.attachToRecyclerView(rv);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
final SessionManager sessionManager = new SessionManager(getActivity());
HashMap<String, String> user = sessionManager.getUserDetail();
String email = user.get("EMAIL");
if(!sessionManager.isLoggin())
{
LinearLayout not_login = root.findViewById(R.id.not_login);
LinearLayout login = root.findViewById(R.id.login);
not_login.setVisibility(View.VISIBLE);
login.setVisibility(View.GONE);
}
else {
LinearLayout not_login = root.findViewById(R.id.not_login);
LinearLayout login = root.findViewById(R.id.login);
not_login.setVisibility(View.GONE);
login.setVisibility(View.VISIBLE);
FirebaseDatabase databaseuser = FirebaseDatabase.getInstance();
DatabaseReference tableuseruser = databaseuser.getReference("Users");
tableuseruser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(isAdded())
{
String convertemail = email.toString().replaceAll("\\.", "_").toString();
Users users = snapshot.child(convertemail).getValue(Users.class);
TextView point = root.findViewById(R.id.profile_point);
TextView name = root.findViewById(R.id.profile_name);
CircleImageView circleImageView = root.findViewById(R.id.profile_image);
name.setText(user.get("NAME"));
point.setText(users.getPoint().toString() + " Point");
if (user.get("PHOTO_PROFILE_PATH").equals(""))
{
Glide.with(getContext()).load("https://cdn.business2community.com/wp-content/uploads/2017/08/blank-profile-picture-973460_640.png").into(circleImageView);
}
else {
Glide.with(getContext()).load(user.get("PHOTO_PROFILE_PATH")).into(circleImageView);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
getbanner();
FirebaseDatabase databasepro = FirebaseDatabase.getInstance();
DatabaseReference tablepro = databasepro.getReference("Product");
tablepro.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(isAdded())
{
listData1.clear();
for (DataSnapshot npsnapshot : snapshot.getChildren()){
Produk l = npsnapshot.getValue(Produk.class);
listData1.add(l);
}
adapter1 = new ProdukAdapter((ArrayList<Produk>) listData1);
recyclerView.setAdapter(adapter1);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
LinearLayout jual = root.findViewById(R.id.btn_jual);
LinearLayout sedekah = root.findViewById(R.id.btn_sedekah);
LinearLayout baitullah = root.findViewById(R.id.btn_baitullah);
ImageView notif = root.findViewById(R.id.notif);
ReddotNotif reddotNotif = new ReddotNotif(getContext());
if(reddotNotif.isRedDot())
{
notif.setImageResource(R.drawable.ic_notify);
}
else {
notif.setImageResource(R.drawable.ic_notif);
}
notif.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
reddotNotif.logout();
startActivity(new Intent(getActivity(), HistorynotificationActivity.class));
}
});
baitullah.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(sessionManager.isLoggin())
{
startActivity(new Intent(getActivity(), MenujubaitullahActivity.class));
}
else {
Intent intent = new Intent(getActivity(), MustloginActivity.class);
intent.putExtra("type", "baitullah");
startActivity(intent);
}
}
});
jual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(sessionManager.isLoggin())
{
startActivity(new Intent(getActivity(), JualsampahActivity.class));
}
else {
Intent intent = new Intent(getActivity(), MustloginActivity.class);
intent.putExtra("type", "jual");
startActivity(intent);
}
}
});
sedekah.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Boolean login = false;
if(sessionManager.isLoggin())
{
startActivity(new Intent(getActivity(), SedekahsampahActivity.class));
}
else {
Intent intent = new Intent(getActivity(), MustloginActivity.class);
intent.putExtra("type", "sedekah");
startActivity(intent);
}
}
});
Button login = root.findViewById(R.id.login_button);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), LoginActivity.class));
}
});
TextView FAQ = root.findViewById(R.id.faq);
String FAQTEXT = "Untuk informasi lebih lanjut, kunjungi halaman FAQ. <font color=#0098FF>di sini </font> ";
FAQ.setText(Html.fromHtml(FAQTEXT));
FAQ.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getActivity(), FaqActivity.class));
}
});
return root;
}
private void getbanner() {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference table = database.getReference("Banner");
table.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(isAdded())
{
sliderData.clear();
for (DataSnapshot npsnapshot : snapshot.getChildren()){
SliderData l = npsnapshot.getValue(SliderData.class);
sliderData.add(l);
}
sliderAdapter = new SliderAdapter((ArrayList<SliderData>) sliderData);
cardSliderViewPager.setAdapter(sliderAdapter);
cardSliderViewPager.setSmallScaleFactor(0.9f);
cardSliderViewPager.setSmallAlphaFactor(0.5f);
cardSliderViewPager.setAutoSlideTime(5);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
this my Category class :
public class Category {
private String id;
private String name;
private String picture_path;
public Category(){
}
public Category(String id, String name, String picture_path) {
this.id = id;
this.name = name;
this.picture_path = picture_path;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPicture_path() {
return picture_path;
}
public void setPicture_path(String picture_path) {
this.picture_path = picture_path;
}
}
and this category at database :
category database
can you help me please, I've been looking for a week where it went wrong, but still can't find it.
I am currently having a trouble on deleting a specific data from my firebase. So basically I have recyclerview wherein my datas are displayed and I have a button in each data display there and that's EDIT button. Whenever I try to click the EDIT button it should intent me to another activity with the same data displayed in the recyclerview and there's a another button displayed there and that's DELETE button. But whenever I try to click the delete button, it deletes all the data from the child. I only need to DELETE the selected ID/Data that is passing when intent occurs.
Edit.
EditResearch.java
package com.example.citeresearchrepository.AdminPackage;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.citeresearchrepository.Model.ResearchRepository;
import com.example.citeresearchrepository.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
public class EditResearchActivity extends AppCompatActivity {
EditText editfilehandler_et,editrepo_title,editrepo_description,editrepo_currentdate;
Button editrepo_savebtn;
ImageView backbtn_editresearch;
DatabaseReference databaseReference;
FirebaseDatabase firebaseDatabase;
StorageReference storageReference;
String researchtitle,researchdate,researchname,researchdescription;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_research);
editfilehandler_et = findViewById(R.id.editfilehandler_et);
editrepo_title = findViewById(R.id.editrepo_title);
editrepo_description = findViewById(R.id.editrepo_description);
editrepo_currentdate = findViewById(R.id.editrepo_currentdate);
editrepo_savebtn = findViewById(R.id.editrepo_savebtn);
backbtn_editresearch = findViewById(R.id.backbtn_editresearch);
Intent intent = getIntent();
researchtitle = intent.getStringExtra("researchtitle");
researchdate = intent.getStringExtra("researchdate");
researchname = intent.getStringExtra("researchname");
researchdescription = intent.getStringExtra("researchdescription");
databaseReference = FirebaseDatabase.getInstance().getReference("ResearchRepository");
storageReference = FirebaseStorage.getInstance().getReference();
editfilehandler_et.setText(researchname);
editrepo_title.setText(researchtitle);
editrepo_currentdate.setText(researchdate);
editrepo_description.setText(researchdescription);
editrepo_savebtn.setEnabled(false);
editfilehandler_et.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectPDF();
}
});
/* Update Files */
backbtn_editresearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), AdminResearchRepoActivity.class));
}
});
}
private void selectPDF(){
Intent intent = new Intent();
intent.setType("application/pdf");
intent.setAction(intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "PDF FILE SELECTED"), 12);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==12 && resultCode == RESULT_OK && data!=null && data.getData()!=null){
editrepo_savebtn.setEnabled(true);
editfilehandler_et.setText(data.getDataString().substring(data.getDataString().lastIndexOf("/") + 1));
editrepo_savebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deletePreviousImage();
uploadResearch(data.getData());
}
});
}
}
private void deleteSelectedRow(){
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("ResearchRepository");
databaseReference.removeValue();
}
private void uploadResearch(Uri data) {
final String filecapture = editfilehandler_et.getText().toString();
final String researchtitle = editrepo_title.getText().toString();
final String researchdescription = editrepo_description.getText().toString();
final String researchtimeline = editrepo_currentdate.getText().toString();
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("File Uploading...");
progressDialog.show();
StorageReference reference = storageReference.child("ResearchRepository" +System.currentTimeMillis() + ".pdf");
reference.putFile(data).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while(!uriTask.isComplete());
Uri uri = uriTask.getResult();
ResearchRepository researchRepository = new ResearchRepository(filecapture,researchtitle,researchdescription,researchtimeline,uri.toString());
databaseReference.child(databaseReference.push().getKey()).setValue(researchRepository);
Toast.makeText(EditResearchActivity.this, "File Uploaded", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
editfilehandler_et.setText("");
editrepo_title.setText("");
editrepo_currentdate.setText("");
editrepo_description.setText("");
startActivity(new Intent(getApplicationContext(), AdminResearchRepoActivity.class));
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
double progress = (100*snapshot.getBytesTransferred())/snapshot.getTotalByteCount();
progressDialog.setMessage("File Uploading..."+(int)progress+"%");
}
});
}
private void deletePreviousImage(){
StorageReference reference = FirebaseStorage.getInstance().getReference().child(researchtitle);
reference.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(EditResearchActivity.this, "Previous File Deleted", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(EditResearchActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
AdminResearchRepoActivity.java
package com.example.citeresearchrepository.AdminPackage;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.citeresearchrepository.AdminAdapter.AdminRepoAdapter;
import com.example.citeresearchrepository.Model.ResearchRepository;
import com.example.citeresearchrepository.R;
import com.example.citeresearchrepository.ViewHolder.AdminResearchRepositoryViewHolder;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class AdminResearchRepoActivity extends AppCompatActivity {
ImageView adminrepo_backbtn;
RecyclerView reporecycler;
FloatingActionButton addresearch_btn;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
AdminRepoAdapter adminRepoAdapter;
ArrayList<ResearchRepository> researchRepositoryArrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_research_repo);
// Buttons
adminrepo_backbtn = findViewById(R.id.backbtn_adminrepo);
addresearch_btn = findViewById(R.id.addresearch_btn);
addresearch_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), AddResearchActivity.class));
}
});
adminrepo_backbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), WelcomeAdminActivity.class));
}
});
// Recycler
reporecycler = findViewById(R.id.reporecycler);
reporecycler.setLayoutManager(new LinearLayoutManager(this));
// Firebase Connection
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference().child("ResearchRepository");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
researchRepositoryArrayList = new ArrayList<ResearchRepository>();
for (DataSnapshot dataSnapshot: snapshot.getChildren()){
ResearchRepository researchRepository = dataSnapshot.getValue(ResearchRepository.class);
researchRepositoryArrayList.add(researchRepository);
}
adminRepoAdapter = new AdminRepoAdapter(AdminResearchRepoActivity.this,researchRepositoryArrayList);
reporecycler.setAdapter(adminRepoAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(AdminResearchRepoActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
AdminRepoAdapter.java
package com.example.citeresearchrepository.AdminAdapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.citeresearchrepository.AdminPackage.EditResearchActivity;
import com.example.citeresearchrepository.Model.ResearchRepository;
import com.example.citeresearchrepository.R;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class AdminRepoAdapter extends RecyclerView.Adapter<AdminRepoAdapter.AdminViewHolder> {
Context context;
ArrayList<ResearchRepository> researchRepositories;
public AdminRepoAdapter(Context c, ArrayList<ResearchRepository> repositories){
context = c;
researchRepositories = repositories;
}
#NonNull
#Override
public AdminViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new AdminViewHolder(LayoutInflater.from(context).inflate(R.layout.admineditrepo_row,parent,false));
}
#Override
public void onBindViewHolder(#NonNull AdminViewHolder holder, final int position) {
holder.researchtitle_view.setText(researchRepositories.get(position).getResearchtitle());
holder.researchdate_view.setText(researchRepositories.get(position).getResearchtimeline());
holder.researchname_view.setText(researchRepositories.get(position).getFilecapture());
holder.researchdescription_view.setText(researchRepositories.get(position).getResearchdescription());
holder.btnpdf_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, EditResearchActivity.class);
intent.putExtra("researchtitle",researchRepositories.get(position).getResearchtitle());
intent.putExtra("researchdate",researchRepositories.get(position).getResearchtimeline());
intent.putExtra("researchname",researchRepositories.get(position).getFilecapture());
intent.putExtra("researchdescription",researchRepositories.get(position).getResearchdescription());
v.getContext().startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return researchRepositories.size();
}
class AdminViewHolder extends RecyclerView.ViewHolder{
public TextView researchtitle_view,researchdate_view,researchname_view,researchdescription_view,researchtitle_url;
public Button btnpdf_edit;
public AdminViewHolder (#NonNull View itemView) {
super(itemView);
researchtitle_view = itemView.findViewById(R.id.researchtitle_view);
researchdate_view = itemView.findViewById(R.id.researchdate_view);
researchname_view = itemView.findViewById(R.id.researchname_view);
researchdescription_view = itemView.findViewById(R.id.researchdescription_view);
researchtitle_url = itemView.findViewById(R.id.researchtitle_view);
btnpdf_edit = itemView.findViewById(R.id.btnpdf_edit);
}
}
}
ResearchRepository.class
package com.example.citeresearchrepository.Model;
public class ResearchRepository {
public String filecapture;
public String researchtitle;
public String researchdescription;
public String researchtimeline;
public String url;
public ResearchRepository() {
}
public ResearchRepository(String filecapture, String researchtitle, String researchdescription, String researchtimeline, String url) {
this.filecapture = filecapture;
this.researchtitle = researchtitle;
this.researchdescription = researchdescription;
this.researchtimeline = researchtimeline;
this.url = url;
}
public String getFilecapture() {
return filecapture;
}
public void setFilecapture(String filecapture) {
this.filecapture = filecapture;
}
public String getResearchtitle() {
return researchtitle;
}
public void setResearchtitle(String researchtitle) {
this.researchtitle = researchtitle;
}
public String getResearchdescription() {
return researchdescription;
}
public void setResearchdescription(String researchdescription) {
this.researchdescription = researchdescription;
}
public String getResearchtimeline() {
return researchtimeline;
}
public void setResearchtimeline(String researchtimeline) {
this.researchtimeline = researchtimeline;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
Here's my realtime-database : https://i.stack.imgur.com/lML0i.png
I just wanna delete the red box.
From what I see you are getting an instance to only the ResearchRepository node instead of the specific child node that you want to delete. You need to keep track of the unique IDs you are pushing on to the ResearchRepository node and pass it in the intent as well;
Add the code to pass the unique ID of the ResearchRepository child you want to delete.
Then do this in your new activity where the delete code is present.
String childToDelete; //retrieve the value from the intent
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("ResearchRepository").child(childToDelete);
databaseReference.removeValue();
This should do it if that is your purpose.
Edit 1:-
I got your point. Please follow the approach I will be showing now and it will work for you.
Edit your class as shown below:-
AdminRepoAdapter.java
public class AdminRepoAdapter extends RecyclerView.Adapter<AdminRepoAdapter.AdminViewHolder> {
Context context;
Map<String,ResearchRepository> researchRepositories;
ArrayList<ResearchRepository> researchRepositoriesHolder;
public AdminRepoAdapter(Context c, Map<String,ResearchRepository> repositories){
context = c;
researchRepositories = repositories;
researchRepositoriesHolder = new ArrayList<>(researchRepositories.values());
}
#NonNull
#Override
public AdminViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new AdminViewHolder(LayoutInflater.from(context).inflate(R.layout.admineditrepo_row,parent,false));
}
#Override
public void onBindViewHolder(#NonNull AdminViewHolder holder, final int position) {
holder.researchtitle_view.setText(researchRepositoriesHolder.get(position).getResearchtitle());
holder.researchdate_view.setText(researchRepositoriesHolder.get(position).getResearchtimeline());
holder.researchname_view.setText(researchRepositoriesHOlder.get(position).getFilecapture());
holder.researchdescription_view.setText(researchRepositoriesHolder.get(position).getResearchdescription());
holder.btnpdf_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Map.Entry<String,ResearchRepository> entry = null; //Just for initialization
for (Map.Entry<String,ResearchRepository> var : researchRepositories.entrySet()) {
if(var.getValue() == researchRepositoriesHolder.get(position)){
entry = var;
break;
}
}
Intent intent = new Intent(context, EditResearchActivity.class);
intent.putExtra("researchtitle",entry.getValue().getResearchtitle());
intent.putExtra("researchdate",entry.getValue().getResearchtimeline());
intent.putExtra("researchname",entry.getValue().getFilecapture());
intent.putExtra("researchdescription",entry.getValue().getResearchdescription());
intent.putExtra("childNodeKey",entry.getKey());
v.getContext().startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return researchRepositoriesHolder.size();
}
class AdminViewHolder extends RecyclerView.ViewHolder{
public TextView researchtitle_view,researchdate_view,researchname_view,researchdescription_view,researchtitle_url;
public Button btnpdf_edit;
public AdminViewHolder (#NonNull View itemView) {
super(itemView);
researchtitle_view = itemView.findViewById(R.id.researchtitle_view);
researchdate_view = itemView.findViewById(R.id.researchdate_view);
researchname_view = itemView.findViewById(R.id.researchname_view);
researchdescription_view = itemView.findViewById(R.id.researchdescription_view);
researchtitle_url = itemView.findViewById(R.id.researchtitle_view);
btnpdf_edit = itemView.findViewById(R.id.btnpdf_edit);
}
}
}
AdminResearchRepoActivity.java
public class AdminResearchRepoActivity extends AppCompatActivity {
ImageView adminrepo_backbtn;
RecyclerView reporecycler;
FloatingActionButton addresearch_btn;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
AdminRepoAdapter adminRepoAdapter;
Map<String, ResearchRepository> researchRepositoryMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_research_repo);
// Buttons
adminrepo_backbtn = findViewById(R.id.backbtn_adminrepo);
addresearch_btn = findViewById(R.id.addresearch_btn);
addresearch_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), AddResearchActivity.class));
}
});
adminrepo_backbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), WelcomeAdminActivity.class));
}
});
// Recycler
reporecycler = findViewById(R.id.reporecycler);
reporecycler.setLayoutManager(new LinearLayoutManager(this));
// Firebase Connection
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference().child("ResearchRepository");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
researchRepositoryMap = (Map)snapshot.getValue()
adminRepoAdapter = new AdminRepoAdapter(AdminResearchRepoActivity.this,researchRepositoryMap);
reporecycler.setAdapter(adminRepoAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(AdminResearchRepoActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
In this way when you pass a Intent from your AdminRepoAdapter to EditResearchActivity you will have the key stored as 'childNodeKey' in your intent.
You can then follow the procedure I mentioned before the edit to delete using the key you got from here.
All my pages use onSupportNavigateUp() function with the same method and it's working. However when I tried to implement in my LessonActivity.java it's not working. Any ideas? It's it because of WebView?
My current working codes for LessonActivity.java:
package com.activity.lesson;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatRatingBar;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ServerValue;
import com.google.firebase.database.ValueEventListener;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.material.components.R;
import com.material.components.activity.pastyears.PastYears;
import com.material.components.activity.practice.Practice;
import com.material.components.adapter.AdapterQuestionToTeacher;
import com.material.components.model.Lessons;
import com.material.components.model.QuestionsToTeacher;
import com.material.components.model.SubChapter;
import com.material.components.utils.Tools;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class LessonActivity extends AppCompatActivity{
public WebView contentWebView;
public ProgressBar progressBar;
public String chapterTitle;
private SharedPreferences analysisSharedPreferences;
private SharedPreferences.Editor editorAnalysisPreferences;
private BottomSheetBehavior mBehavior;
private BottomSheetDialog mBottomSheetDialog;
private View bottom_sheet;
private BottomNavigationView navigation;
public ArrayList<QuestionsToTeacher> questionsToTeacherList = new ArrayList<>();
private AdapterQuestionToTeacher adapterQuestionToTeacher;
private RecyclerView questionListRecyclerView;
private String subjectId;
private String chapterId;
private String subchapterId;
private TextView question_content;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lesson);
contentWebView = findViewById(R.id.contentWebView);
progressBar = findViewById(R.id.progressBarContent);
question_content = findViewById(R.id.question_content);
Tools.setSystemBarColor(this,R.color.black);
String qContent = question_content.getText().toString().trim();
if(qContent.isEmpty())
{
question_content.setVisibility(View.GONE);
}else
{
question_content.setVisibility(View.VISIBLE);
}
initToolbar();
String subChapterId = getIntent().getStringExtra("subchapter_id");
getLessonData(subChapterId);
analysisSharedPreferences = getApplicationContext().getSharedPreferences("AnalysisSharedPreferences",MODE_PRIVATE);
editorAnalysisPreferences = analysisSharedPreferences.edit();
subjectId = analysisSharedPreferences.getString("subjectId","");
chapterId = analysisSharedPreferences.getString("chapterId","");
subchapterId = analysisSharedPreferences.getString("subchapterId","");
bottom_sheet = findViewById(R.id.bottom_sheet);
mBehavior = BottomSheetBehavior.from(bottom_sheet);
navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_question_list:
showQuestionList();
return true;
}
return false;
}
});
}
private void getQuestionList() {
GsonBuilder builder = new GsonBuilder();
final Gson gson = builder.create();
questionsToTeacherList.clear();
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference databaseReference = firebaseDatabase.getReference();
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
databaseReference.child("ask_teachers/students/"+firebaseAuth.getUid()+"/subjects/"+subjectId+"/chapters/"+chapterId+"/subchapters/"+subchapterId+"/questions").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot: dataSnapshot.getChildren())
{
String dataReceived = gson.toJson(snapshot.getValue());
System.out.println(snapshot.getValue());
QuestionsToTeacher questionsToTeacher = gson.fromJson(dataReceived,QuestionsToTeacher.class);
questionsToTeacherList.add(questionsToTeacher);
}
adapterQuestionToTeacher.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void showQuestionList() {
if (mBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
mBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
final View view = getLayoutInflater().inflate(R.layout.sheet_question_list, null);
adapterQuestionToTeacher = new AdapterQuestionToTeacher(questionsToTeacherList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(LessonActivity.this);
questionListRecyclerView = view.findViewById(R.id.questionListRecyclerView);
questionListRecyclerView.setItemAnimator(new DefaultItemAnimator());
questionListRecyclerView.setNestedScrollingEnabled(false);
questionListRecyclerView.setHasFixedSize(true);
questionListRecyclerView.setLayoutManager(layoutManager);
questionListRecyclerView.setAdapter(adapterQuestionToTeacher);
adapterQuestionToTeacher.setOnClickListener(new AdapterQuestionToTeacher.OnClickListener() {
#Override
public void onItemClick(View view, QuestionsToTeacher obj, int pos) {
question_content.setVisibility(View.VISIBLE);
question_content.setText(obj.messages);
mBottomSheetDialog.dismiss();
}
});
(view.findViewById(R.id.bt_close)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mBottomSheetDialog.dismiss();
}
});
mBottomSheetDialog = new BottomSheetDialog(this);
mBottomSheetDialog.setContentView(view);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mBottomSheetDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
mBottomSheetDialog.show();
mBottomSheetDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
mBottomSheetDialog = null;
}
});
getQuestionList();
}
private void getLessonData(String subChapterId)
{
FirebaseDatabase.getInstance().getReference().child("lessons/"+subChapterId+"/lessons_data")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String lessonDisplay = "";
for(DataSnapshot snapshot: dataSnapshot.getChildren())
{
System.out.println("lesson_inner_content");
System.out.println(snapshot.getValue());
lessonDisplay += snapshot.getValue();
}
contentWebView.getSettings().setJavaScriptEnabled(true);
contentWebView.setWebViewClient(new AppWebViewClients(progressBar));
contentWebView.loadData(String.valueOf(lessonDisplay),"text/html", "UTF-8");
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public class AppWebViewClients extends WebViewClient {
private ProgressBar progressBar;
public AppWebViewClients(ProgressBar progressBar) {
this.progressBar=progressBar;
progressBar.setVisibility(View.VISIBLE);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
}
private void initToolbar() {
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
chapterTitle = getIntent().getStringExtra("subChapterTitle");
setTitle(chapterTitle);
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
public void openSubMenu(View v)
{
PopupMenu popup = new PopupMenu(v.getContext(), v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu_lesson_more, popup.getMenu());
popup.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_lesson,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.askTeacher)
{
showQuestionEntryDialog();
}
if(id == R.id.practice)
{
Intent gotoPractice = new Intent(LessonActivity.this, Practice.class);
startActivity(gotoPractice);
}
if(id == R.id.pastYears)
{
Intent gotoPastYears = new Intent(LessonActivity.this, PastYears.class);
startActivity(gotoPastYears);
}
return true;
}
private void showQuestionEntryDialog() {
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // before
dialog.setContentView(R.layout.dialog_ask_teacher_question_entry);
dialog.setCancelable(true);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
final EditText et_post = dialog.findViewById(R.id.et_post);
dialog.findViewById(R.id.bt_cancel).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.findViewById(R.id.bt_submit).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String review = et_post.getText().toString().trim();
if (review.isEmpty()) {
Toast.makeText(getApplicationContext(), "Please fill review text", Toast.LENGTH_SHORT).show();
}else
{
submitQuestion(review, dialog);
}
}
});
dialog.show();
dialog.getWindow().setAttributes(lp);
}
private void submitQuestion(String message, final Dialog dialog)
{
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
String uuid = currentFirebaseUser.getUid();
DatabaseReference databaseReference = firebaseDatabase.getReference();
HashMap<Object,Object> messagesData = new HashMap<>();
messagesData.put("subject_id",subjectId);
messagesData.put("chapter_id",chapterId);
messagesData.put("subchapter_id",subchapterId);
messagesData.put("messages",message);
messagesData.put("status","pending");
messagesData.put("dt_added", ServerValue.TIMESTAMP);
databaseReference.child("ask_teachers/students/"+uuid+"/subjects/"+subjectId+"/chapters/"+chapterId+"/subchapters/"+subchapterId+"/questions/").push().setValue(messagesData, new DatabaseReference.CompletionListener(){
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
Toast.makeText(LessonActivity.this, "Successfully added to Ask Teacher list", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
}
}
onSupportNavigateUp() is not working because you're also overriding onOptionsItemSelected(). Since you return true; from onOptionsItemSelected(), you basically tell Android that you handle all item clicks by yourself and it doesn't need to do something.
You have two options now. Either call super.onOptionsItemSelected() like:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.askTeacher) {
showQuestionEntryDialog();
return true; // don't forget to return true after your action
}
// ... handle all your other items
return super.onOptionsItemSelected(item);
}
Or you handle the back button click by yourself:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
// navigate up on back button click
if (id == android.R.id.home) {
NavUtils.navigateUpFromSameTask(this);
return true;
}
// ... handle all your other items
return true;
}
By the way, I think overriding onSupportNavigateUp() is not needed at all. Up navigation works "out of the box" (at least for me), as long as I don't override onOptionsItemSelected() or call super.onOptionsItemSelected(item); from within it.
this is my first post here, so any guidance at all is appreciated.
I'm having an issue when others download my app. It causes the App to crash on launch. It works perfectly when I install updates and seems to be an issue stemming from users not having a Firebase UID created when first launching.
Here is Main Activity Code:
package com.example.android.cellavino;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.cellavino.PojoDirectory.UI2.UserDetailsPojo;
import com.example.android.cellavino.UserInterface.WineAdapter;
import com.example.android.cellavino.UserInterface2.WineDetails.CreateNewWine;
import com.example.android.cellavino.UserInterface2.CreateTasting.MyTastings;
import com.example.android.cellavino.UserInterface2.EditProfile.EditProfile;
import com.example.android.cellavino.UserInterface2.JoinTasting.JoinTasting;
import com.example.android.cellavino.UserInterface2.WineDetails.MyWinesList;
import com.example.android.cellavino.Utils.Constants;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import com.firebase.ui.auth.AuthUI;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ServerValue;
import com.google.firebase.remoteconfig.FirebaseRemoteConfig;
import com.google.firebase.storage.FirebaseStorage;
import java.util.Arrays;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private static final String LOG_TAG = MainActivity.class.getSimpleName();
public static final String ANONYMOUS = "anonymous";
public static final int RC_SIGN_IN = 1;
public String mUsername;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mWineDatabaseReference;
private DatabaseReference mUserDatabaseReference;
private DatabaseReference mMyWinesReference;
private ChildEventListener mChildEventListener;
private FirebaseRemoteConfig mFirebaseRemoteConfig;
private FirebaseStorage mFirebaseStorage;
private WineAdapter mWineAdapter;
private ListView mWineListView;
private RecyclerView mWineRecyclerView;
private RecyclerView.Adapter mAdapter;
private ProgressBar mProgressBar;
private RecyclerView.LayoutManager mLayoutManager;
private DrawerLayout mNavigationDrawerLayout;
private ActionBarDrawerToggle mActionBarDrawerToggle;
private ListView mWineInformation;
private TextView mWineName;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private ListView mDrawerList;
private String[] mMenuOptions;
private Uri userProfilePic;
private TextView mUsernameTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setContentView(R.layout.my_wines_list);
//setContentView(R.layout.activity_container);
//getSupportFragmentManager().beginTransaction().replace(R.id.container, new MyWinesListFragment()).commit();
//Initialise Firebase
Firebase.setAndroidContext(this);
mUsername = ANONYMOUS;
//mTitle = mDrawerTitle = getTitle();
mFirebaseDatabase = FirebaseDatabase.getInstance();
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseStorage = FirebaseStorage.getInstance();
mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
//WineDatabase in Firebase initialisation
mWineDatabaseReference = mFirebaseDatabase.getReference().child("Wine Details");
mUserDatabaseReference = mFirebaseDatabase.getReference().child("Users");
mMyWinesReference = mFirebaseDatabase.getReference().child("Users").child("myWines");
//initialising the views
//ListView mWineListView = (ListView) findViewById(R.id.wineListView);
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
//user is signed in
onSignedInInialise(user.getDisplayName());
} else {
//user is signed out
onSignedOutCleanup();
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setProviders(Arrays.asList(
new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build()))
.build(),
RC_SIGN_IN);
}
}
};
//add code that will bring up the Add_Wine screen when a user clicks on the floating action button for addwine.
FloatingActionButton addWineFab = (FloatingActionButton) findViewById(R.id.addWineFab);
addWineFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, CreateNewWine.class);
startActivity(intent);
}
});
//initialise view_my_wines button click listener
Button viewMyWinesButton = (Button) findViewById(R.id.view_my_wines);
viewMyWinesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, MyWinesList.class);
startActivity(intent);
}
});
//initialise edit_profile button click listener
Button editProfileButton = (Button) findViewById(R.id.edit_profile);
editProfileButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, EditProfile.class);
startActivity(intent);
}
});
//initialise edit_profile button click listener
Button createTastingButton = (Button) findViewById(R.id.create_tasting);
createTastingButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, MyTastings.class);
startActivity(intent);
}
});
//initialise edit_profile button click listener
Button joinTastingButton = (Button) findViewById(R.id.join_tasting);
joinTastingButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, JoinTasting.class);
startActivity(intent);
}
});
FirebaseUser user = mFirebaseAuth.getCurrentUser();
String userName = user.getDisplayName();
if (user != null) {
TextView mUsernameTextView = (TextView) findViewById(R.id.user_name);
mUsernameTextView.setText(userName);
} else {
TextView mUsernameTextView = (TextView) findViewById(R.id.user_name);
mUsernameTextView.setVisibility(View.GONE);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
FirebaseUser user = mFirebaseAuth.getCurrentUser();
String uid = user.getUid();
String userName = user.getDisplayName();
String userEmail = user.getEmail();
Uri userProfilePic = user.getPhotoUrl();
createUserInFirebaseHelper(uid, userName, userEmail);
Toast.makeText(MainActivity.this, "Hello " + userName + "!", Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(MainActivity.this, "Sign in cancelled", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void createUserInFirebaseHelper(String uid, String userName, String userEmail) {
final String mUserName = userName;
final String mUserEmail = userEmail;
final Firebase userDetailLocation = new Firebase(Constants.FIREBASE_URL_LOCATION_USERS).child(uid);
//See if there is already a user (for example, if they already logged in with an associated google account
userDetailLocation.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(com.firebase.client.DataSnapshot dataSnapshot) {
// If there is no user, make one
if (dataSnapshot.getValue() == null) {
//Set raw version of date to the ServerValue.TIMESTAMP value and save into dateCreatedMap
HashMap<String, Object> timestampJoined = new HashMap<>();
timestampJoined.put(Constants.FIREBASE_PROPERTY_TIMESTAMP, ServerValue.TIMESTAMP);
UserDetailsPojo newUser = new UserDetailsPojo(mUserName, mUserEmail, timestampJoined);
userDetailLocation.setValue(newUser);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.d(LOG_TAG, getString(R.string.log_error_occurred) + firebaseError.getMessage());
}
});
}
//When the app comes back from background state etc
#Override
protected void onResume() {
super.onResume();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
//When the app goes to background state
#Override
protected void onPause() {
super.onPause();
if (mAuthStateListener != null) {
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
}
detachDatabaseReadListener();
//mWineAdapter.clear();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_navigation_drawer, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//if (mActionBarDrawerToggle.onOptionsItemSelected(item)) {
// return true;
//}
switch (item.getItemId()) {
case R.id.sign_out_menu:
//sign out
AuthUI.getInstance().signOut(this);
return true;
/*
case R.id.menu_add_wine:
//add wine
Intent intent = new Intent(MainActivity.this, AddWine.class);
startActivity(intent);
return true;
case R.id.view_my_wines:
//view the working wine list Andrews Wines
Intent intent2 = new Intent(MainActivity.this, MyWinesList.class);
startActivity(intent2);
return true;
case R.id.test_option:
//view the test screens for Andrews Wines
Intent intent3 = new Intent(MainActivity.this, Login.class);
startActivity(intent3);
return true;
*/
default:
return super.onOptionsItemSelected(item);
}
}
private void onSignedInInialise(String username) {
mUsername = username;
//attachDatabaseReadListener();
//this code adds a new user name each time it logs in.
//mUserDatabaseReference.push().setValue(username);
}
private void onSignedOutCleanup() {
mUsername = ANONYMOUS;
//mWineAdapter.clear();
detachDatabaseReadListener();
}
/*
private void attachDatabaseReadListener() {
if (mChildEventListener == null) {
mChildEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
WineDetails wineDetails = dataSnapshot.getValue(WineDetails.class);
//mWineAdapter.add(wineDetails);
}
#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) {
}
};
mWineDatabaseReference.addChildEventListener(mChildEventListener);
}
}
*/
private void detachDatabaseReadListener() {
if (mChildEventListener != null) {
mWineDatabaseReference.removeEventListener(mChildEventListener);
mChildEventListener = null;
}
}
private void initializeScreen(View rootView) {
mWineInformation = (ListView) rootView.findViewById(R.id.wine_list_item_details);
mWineName = (TextView) rootView.findViewById(R.id.wine_name);
}
}
How can I adjust it so it checks to see if a user has a profile and if not directs them to the login page?
Thanks in advance.
I figured it out. I was calling getDisplayName() prior to checking authentication.
Thanks for the pointers in how to post a question. I waited 6 months before posting one as I wasn't really sure how/what to ask. Now I know. :)