I don't get the error when i run the app everything works fine, but when i click on the send message button the app crashes but the message still gets sent. below is my code for the chatActivity and logcat message
package com.paddi.paddi.paddi;
public class ChatActivity extends AppCompatActivity
{
private String messageReceiverId;
private String messageReceiverName;
// private Toolbar ChatToolBar;
private TextView userNameTitle;
private TextView userLastSeen;
private CircleImageView userChatProfileImage;
private ImageButton SendMessageButton;
// private ImageButton SelectImageButton;
private EditText InputMessageText;
FirebaseUser fuser;
DatabaseReference rootRef;
private FirebaseAuth mAuth;
private String messageSenderId;
private RecyclerView userMessagesList;
private final List<Messages> messageList = new ArrayList<>();
private LinearLayoutManager linearLayoutManager;
private MessageAdapter messageAdapter;
private static int Gallery_Pick = 1;
private StorageReference MessageImageStorageRef;
private ProgressDialog loadingBar;
private String downloadImageUrl;
Intent intent;
ValueEventListener seenListener;
String userid;
APIServiceFragment apiService;
boolean notify = false;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
rootRef = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
messageSenderId = mAuth.getCurrentUser().getUid();
messageReceiverId = getIntent().getExtras().get("visit_user_id").toString();
messageReceiverName = getIntent().getExtras().get("user_name").toString();
MessageImageStorageRef = FirebaseStorage.getInstance().getReference().child("Messages_Pictures");
apiService = Client.getClient("https://fcm.googleapis.com/").create(APIServiceFragment.class);
// ChatToolBar = (Toolbar) findViewById(R.id.chat_bar_layout);
// setSupportActionBar(ChatToolBar);
loadingBar = new ProgressDialog(this);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
LayoutInflater layoutInflater = (LayoutInflater)
this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View action_bar_view = layoutInflater.inflate(R.layout.chat_custom_bar, null);
actionBar.setCustomView(action_bar_view);
userNameTitle = (TextView) findViewById(R.id.custom_profile_name);
userLastSeen = (TextView) findViewById(R.id.custom_user_last_seen);
userChatProfileImage = (CircleImageView) findViewById(R.id.custom_profile_image_last_seen);
SendMessageButton = (ImageButton) findViewById(R.id.send_message_btn);
// SelectImageButton = (ImageButton) findViewById(R.id.select_image);
InputMessageText = (EditText) findViewById(R.id.input_message);
messageAdapter = new MessageAdapter(messageList);
userMessagesList = (RecyclerView) findViewById(R.id.messages_list_of_users);
linearLayoutManager = new LinearLayoutManager(this);
userMessagesList.setHasFixedSize(true);
userMessagesList.setLayoutManager(linearLayoutManager);
userMessagesList.setAdapter(messageAdapter);
FetchMessages();
userNameTitle.setText(messageReceiverName);
rootRef.child("Users").child(messageReceiverId).addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
final String online = dataSnapshot.child("online").getValue().toString();
final String userThumb = dataSnapshot.child("user_thumb_image").getValue().toString();
Picasso.with(ChatActivity.this).load(userThumb).fit().centerInside().networkPolicy(NetworkPolicy.OFFLINE).placeholder(R.drawable.default_profile)
.into(userChatProfileImage, new Callback() {
#Override
public void onSuccess()
{
}
#Override
public void onError()
{
Picasso.with(ChatActivity.this).load(userThumb).fit().centerInside().placeholder(R.drawable.default_profile).into(userChatProfileImage);
}
});
if (online != null) {
if (online.equals("true"))
{
userLastSeen.setText("online");
}
else
{
LastSeenTime getTime = new LastSeenTime();
long last_seen = Long.parseLong(online);
//problem with last seen time here
String lastSeenDisplayTime = getTime.getTimeAgo(last_seen, getApplicationContext()).toString();
userLastSeen.setText(lastSeenDisplayTime);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
});
SendMessageButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
SendMessage();
}
});
// SelectImageButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v)
// {
// Intent galleryIntent = new Intent();
// galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// galleryIntent.setType("image/*");
// startActivityForResult(galleryIntent, Gallery_Pick);
//}
//});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==Gallery_Pick && resultCode==RESULT_OK &&data!=null)
{
loadingBar.setTitle("Sending Image");
loadingBar.setMessage("Please Wait");
loadingBar.show();
Uri ImageUri = data.getData();
final String message_sender_ref = "Messages/" + messageSenderId + "/" + messageReceiverId;
final String message_receiver_ref = "Messages/" + messageReceiverId + "/" + messageSenderId;
DatabaseReference user_message_key = rootRef.child("Messages").child(messageSenderId)
.child(messageReceiverId).push();
final String message_push_id = user_message_key.getKey();
final StorageReference filePath = MessageImageStorageRef.child(message_push_id + ".jpg");
final StorageTask<UploadTask.TaskSnapshot> taskSnapshotStorageTask = filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
downloadImageUrl = filePath.getDownloadUrl().toString();
// return filePath.getDownloadUrl();
Map messageTextBody = new HashMap();
messageTextBody.put("message", downloadImageUrl);
messageTextBody.put("isseen", true);
messageTextBody.put("type", "image");
messageTextBody.put("time", ServerValue.TIMESTAMP);
messageTextBody.put("from", messageSenderId);
messageTextBody.put("to", messageReceiverId);
Map messageBodyDetails = new HashMap();
messageBodyDetails.put(message_sender_ref + "/" + message_push_id, messageTextBody);
messageBodyDetails.put(message_receiver_ref + "/" + message_push_id, messageTextBody);
rootRef.updateChildren(messageBodyDetails, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError != null) {
Log.d("Chat_Log", databaseError.getMessage().toString());
}
InputMessageText.setText("");
loadingBar.dismiss();
}
});
Toast.makeText(ChatActivity.this, "Picture Sent Successfully.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
} else {
Toast.makeText(ChatActivity.this, "Picture not sent, Try again", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
private void FetchMessages()
{
rootRef.child("Messages").child(messageSenderId).child(messageReceiverId)
.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s)
{
if (dataSnapshot.exists())
{
Messages messages = dataSnapshot.getValue(Messages.class);
messageList.add(messages);
messageAdapter.notifyDataSetChanged();
userMessagesList.smoothScrollToPosition(userMessagesList.getAdapter().getItemCount());
}
}
#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)
{
}
});
// seenMessage(userid);
}
private void seenMessage(final String userid) //add String and userid
{
rootRef = FirebaseDatabase.getInstance().getReference("Messages");
seenListener = rootRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
for (DataSnapshot snapshot : dataSnapshot.getChildren())
{
Messages messages = snapshot.getValue(Messages.class);
if (messages.getTo().equals(fuser.getUid()) && messages.getFrom().equals(ChatActivity.this.userid))//change messages to userid
{
Map messageTextBody = new HashMap();
messageTextBody.put("isseen", true);
snapshot.getRef().updateChildren(messageTextBody);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void SendMessage()
{
notify = true;
String messageText = InputMessageText.getText().toString();
if (TextUtils.isEmpty(messageText))
{
Toast.makeText(ChatActivity.this,
"Input message", Toast.LENGTH_SHORT).show();
}
else
{
String message_sender_ref = "Messages/" + messageSenderId + "/" + messageReceiverId;
final String message_receiver_ref = "Messages/" + messageReceiverId + "/" + messageSenderId;
DatabaseReference user_message_key = rootRef.child("Messages").child(messageSenderId)
.child(messageReceiverId).push();
String message_push_id = user_message_key.getKey();
Map messageTextBody = new HashMap();
messageTextBody.put("message", messageText);
messageTextBody.put("isseen", false);
messageTextBody.put("type", "text");
messageTextBody.put("time", ServerValue.TIMESTAMP);
messageTextBody.put("from", messageSenderId);
messageTextBody.put("to", messageReceiverId);
Map messageBodyDetails = new HashMap();
messageBodyDetails.put(message_sender_ref + "/" + message_push_id, messageTextBody);
messageBodyDetails.put(message_receiver_ref + "/" + message_push_id, messageTextBody);
rootRef.updateChildren(messageBodyDetails).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task)
{
if (task.isSuccessful())
{
Toast.makeText(ChatActivity.this, "Message Sent", Toast.LENGTH_SHORT).show();
InputMessageText.setText("");
}
else
{
String message = task.getException().getMessage();
Toast.makeText(ChatActivity.this, "Error:" + message, Toast.LENGTH_SHORT).show();
InputMessageText.setText("");
}
}
});
**i tried sending chat notification with the code below
and that was what triggered the error the messages still get sent but the app crashes and restarts itself.**
final String msg = messageText;
rootRef = FirebaseDatabase.getInstance().getReference("Users").child(fuser.getUid());
rootRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
User user = dataSnapshot.getValue(User.class);
if (notify) {
sendNotification(message_receiver_ref, user.getUsername(), msg);
}
notify = false;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
private void sendNotification(String message_receiver_ref, final String username, final String message)
{
DatabaseReference tokens = FirebaseDatabase.getInstance().getReference("Tokens");
Query query = tokens.orderByKey().equalTo(message_receiver_ref);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
for (DataSnapshot snapshot: dataSnapshot.getChildren())
{
Token token = snapshot.getValue(Token.class);
Data data = new Data(fuser.getUid(), R.mipmap.app_icon, username+": "+message, "New Message",
userid);
Sender sender = new Sender(data, token.getToken());
apiService.sendNotification(sender)
.enqueue(new retrofit2.Callback<MyResponse>() {
#Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response)
{
if (response.code() == 200)
{
if (response.body().success != 1)
{
Toast.makeText(ChatActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onFailure(Call<MyResponse> call, Throwable t)
{
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
}
});
}
}
this is the logcat below
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at com.paddi.paddi.paddi.ChatActivity.SendMessage(ChatActivity.java:504)
at com.paddi.paddi.paddi.ChatActivity.access$200(ChatActivity.java:58)
at com.paddi.paddi.paddi.ChatActivity$2.onClick(ChatActivity.java:251)
at android.view.View.performClick(View.java:5274)
at android.view.View$PerformClick.run(View.java:21543)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5765)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
You are getting the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
Because your fuser object is not initialized. To solve this, please add the following line of code in your onCreate() method:
fuser = FirebaseAuth.getInstance().getCurrentUser().getUid();
Related
I am developing an e-commerce android application in which i have two sides(admin side and user side). I have implemented in-app messaging in my application where user can send message to admin and admin can send message to user. Now, i want to add notifications to this part that when a admin or user sends message the other side receives notification if it is in the app because i want to do this without server side code. I tried googling it but couldn't find any good solution. So can anyone help?
Here is my chat class for user:
chat_messages_view_panel = (LinearLayout)findViewById(R.id.chat_messages_view_panel);
chat_messages_scroll_view = (ScrollView)findViewById(R.id.chat_messages_scroll_view);
chatImagesRef = FirebaseStorage.getInstance().getReference().child("Chat Images");
FirebaseDatabase.getInstance().getReference().child("Admins").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot item : snapshot.getChildren()) {
admin = item.getValue(Admin.class);
break;
}
loadMessages();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
FirebaseDatabase.getInstance().getReference().child("Messages").child(Prevelent.onlineUser.getEmail()).
addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot)
{
for(DataSnapshot item: snapshot.getChildren())
{
Message message = item.getValue(Message.class);
if(!message_ids.contains(message.getId()))
{
message_ids.add(message.getId());
addMessage(message);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
sendButton = (ImageButton)findViewById(R.id.sendMessage);
messageContent = (EditText)findViewById(R.id.chat_message_box);
sendPictureButton = (ImageButton) findViewById(R.id.uploadImage);
loadingBar = new ProgressDialog(this);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(messageContent.getText().toString().equals("")){
return;
}
Calendar calendar = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("yyyy MM, dd");
String saveCurrentDate = currentDate.format(calendar.getTime());
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss:SSS a");
String saveCurrentTime = currentTime.format(calendar.getTime());
DatabaseReference messageRef = FirebaseDatabase.getInstance().getReference();
Map<String, Object> userdataMap = new HashMap<>();
userdataMap.put("id", Prevelent.onlineUser.getEmail() + " : " + saveCurrentDate + " " + saveCurrentTime);
userdataMap.put("content", messageContent.getText() + "");
userdataMap.put("sentByEmail", Prevelent.onlineUser.getEmail());
userdataMap.put("sentByName", Prevelent.onlineUser.getName());
userdataMap.put("sentToEmail", admin.getEmail());
userdataMap.put("sentToName", admin.getName());
userdataMap.put("sentAt", saveCurrentDate + " " + saveCurrentTime);
userdataMap.put("messageType", "text");
messageRef.child("Messages").child(Prevelent.onlineUser.getEmail()).child(saveCurrentDate + " " + saveCurrentTime).
updateChildren(userdataMap)
.addOnCompleteListener(new OnCompleteListener<Void>(){
#Override
public void onComplete(#NonNull Task<Void> task) {
messageContent.setText("");
}
});
}
});
sendPictureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
OpenGallery();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==GalleryPick && resultCode==RESULT_OK && data!=null)
{
ImageUri = data.getData();
AlertDialog.Builder alertadd = new AlertDialog.Builder(chatActivity.this);
LayoutInflater factory = LayoutInflater.from(chatActivity.this);
final View view = factory.inflate(R.layout.alertdialog_imageview_layout, null);
ImageView imageView = view.findViewById(R.id.dialog_imageview);
imageView.setImageURI(ImageUri);
alertadd.setView(view);
alertadd.setCancelable(false);
alertadd.setPositiveButton("Upload", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
loadingBar.setTitle("Picture Upload");
loadingBar.setMessage("Please wait while your image is being uploaded");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
UploadImage();
dlg.dismiss();
}
});
alertadd.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
dlg.dismiss();
}
});
alertadd.show();
}
}
public void UploadImage(){
Calendar calendar = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("yyyy MM, dd");
saveCurrentDate = currentDate.format(calendar.getTime());
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss:SSS a");
saveCurrentTime = currentTime.format(calendar.getTime());
pictureRandomKey = saveCurrentDate + saveCurrentTime;
final StorageReference filePath = chatImagesRef.child(ImageUri.getLastPathSegment() + pictureRandomKey + ".jpg");
final UploadTask uploadTask = filePath.putFile(ImageUri);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e)
{
String message = e.toString();
Toast.makeText(chatActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
{
loadingBar.cancel();
Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception
{
if (!task.isSuccessful())
{
throw task.getException();
}
downloadImageUrl = filePath.getDownloadUrl().toString();
return filePath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task)
{
if (task.isSuccessful())
{
downloadImageUrl = task.getResult().toString();
DatabaseReference messageRef = FirebaseDatabase.getInstance().getReference();
Map<String, Object> userdataMap = new HashMap<>();
userdataMap.put("id", Prevelent.onlineUser.getEmail() + " : " + saveCurrentDate + " " + saveCurrentTime);
userdataMap.put("content", downloadImageUrl);
userdataMap.put("sentByEmail", Prevelent.onlineUser.getEmail());
userdataMap.put("sentByName", Prevelent.onlineUser.getName());
userdataMap.put("sentToEmail", admin.getEmail());
userdataMap.put("sentToName", admin.getName());
userdataMap.put("sentAt", saveCurrentDate + " " + saveCurrentTime);
userdataMap.put("messageType", "picture");
messageRef.child("Messages").child(Prevelent.onlineUser.getEmail()).child(saveCurrentDate + " " + saveCurrentTime).
updateChildren(userdataMap)
.addOnCompleteListener(new OnCompleteListener<Void>(){
#Override
public void onComplete(#NonNull Task<Void> task) {
messageContent.setText("");
}
});
}
}
});
}
});
}
private void addMessage(Message message)
{
if(message.getMessageType().equals("text")){
if(message.getSentByEmail().equals(Prevelent.onlineUser.getEmail()))
{
addMyMessage(message);
}
else
{
addTheirMessage(message);
}
}else{
int id = View.generateViewId();
imagesUrl.put(id, message.getContent());
if(message.getSentByEmail().equals(Prevelent.onlineUser.getEmail()))
{
addMyMessageImage(message, id);
}
else
{
addTheirMessageImage(message, id);
}
}
}
private void addTheirMessageImage(Message message, int id) {
try {
View v = LayoutInflater.from(chatActivity.this).inflate(R.layout.their_message_image, null);
TextView sender_name_view = v.findViewById(R.id.sender_name_view);
ImageView imageView = v.findViewById(R.id.receivedImageView);
TextView message_time = v.findViewById(R.id.received_message_box_time);
sender_name_view.setText(message.getSentByName());
Picasso.get().load(message.getContent()).into(imageView);
message_time.setText(getMomentAgo(message.getSentAt()));
imageView.setId(id);
chat_messages_view_panel.addView(v);
scrollChatToBottom();
}catch (Exception ignored)
{
}
}
private void addMyMessageImage(Message message, int id) {
try {
View v = LayoutInflater.from(chatActivity.this).inflate(R.layout.my_message_image, null);
ImageView imageView = v.findViewById(R.id.sentImageView);
TextView message_time = v.findViewById(R.id.sent_message_box_time);
Picasso.get().load(message.getContent()).into(imageView);
message_time.setText(getMomentAgo(message.getSentAt()));
imageView.setId(id);
chat_messages_view_panel.addView(v);
scrollChatToBottom();
}catch (Exception ignored)
{
}
}
private void addTheirMessage(Message message)
{
try {
View v = LayoutInflater.from(chatActivity.this).inflate(R.layout.their_message, null);
TextView sender_name_view = v.findViewById(R.id.sender_name_view);
TextView message_view = v.findViewById(R.id.sender_message_body);
TextView message_time = v.findViewById(R.id.received_message_box_time);
sender_name_view.setText(message.getSentByName());
message_view.setText(message.getContent());
message_time.setText(getMomentAgo(message.getSentAt()));
chat_messages_view_panel.addView(v);
scrollChatToBottom();
}catch (Exception ignored)
{
}
}
private void addMyMessage(Message message)
{
try {
View v = LayoutInflater.from(chatActivity.this).inflate(R.layout.my_message, null);
TextView message_view = v.findViewById(R.id.my_message_body);
TextView message_time = v.findViewById(R.id.sent_message_box_time);
message_view.setText(message.getContent());
message_time.setText(getMomentAgo(message.getSentAt()));
chat_messages_view_panel.addView(v);
scrollChatToBottom();
}catch (Exception ignored)
{
}
}
public void scrollChatToBottom() {
chat_messages_scroll_view.post(new Runnable() {
#Override
public void run() {
chat_messages_scroll_view.fullScroll(ScrollView.FOCUS_DOWN);
}
});
}
private void OpenGallery()
{
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GalleryPick);
}
#SuppressLint("SimpleDateFormat")
public String getMomentAgo(String date_time){
try{
SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy MM, dd HH:mm:ss:SSS a");
SimpleDateFormat destFormat = new SimpleDateFormat("dd MMM, HH:mm a");
Date convertedDate = sourceFormat.parse(date_time);
if (convertedDate != null) {
return destFormat.format(convertedDate);
}
}catch (Exception ignored){}
return "";
}
public void imageClick(View view)
{
Dialog builder = new Dialog(this);
builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
builder.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
//nothing;
}
});
ImageView imageView = new ImageView(this);
Picasso.get().load(imagesUrl.get(view.getId())).into(imageView);
builder.addContentView(imageView, new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
builder.show();
}
public void loadMessages(){
FirebaseDatabase.getInstance().getReference().child("Messages").child(Prevelent.onlineUser.getEmail()).
addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot)
{
for(DataSnapshot item: snapshot.getChildren())
{
Message message = item.getValue(Message.class);
if(!message_ids.contains(message.getId()))
{
message_ids.add(message.getId());
addMessage(message);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
You can follow this tutorial:
Send Device-to-Device Push Notifications Without Server-side Code
Update
You can Listen for a database specific child and show notification when there is a change happens (Simulating Server Push notification)
I am showing Firebase data in a RecyclerView and it is working fine.
I have also implemented a SwipeRefreshLayout and when user swipe it, it is getting latest data from Firebase. But whenever I swipe it more than once, it is showing duplicate values although I am clearing the ArrayList and also I am using `swipeRefresh.setEnabled(true)``
Here I am implementing SwipeRefreshLayout:
swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getData();
if (swipeRefresh.isEnabled())
swipeRefresh.setEnabled(false);
}
});
Here is my getData() function:
public void getData() {
pd.setTitle("Loading Data");
pd.setMessage("Please Wait...");
pd.setCancelable(false);
pd.show();
infoList = new ArrayList<>();
distributorList = new ArrayList<>();
infoList.clear();
distributorList.clear();
countChilds = 0;
counter = 0;
final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
final DatabaseReference hotelRef = rootRef.child("Orders");
hotelRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
final String key = String.valueOf(dataSnapshot.getKey());
final String hotelName = String.valueOf(dataSnapshot.child("hotelName").getValue());
final String location = String.valueOf(dataSnapshot.child("location").getValue());
final String quantity = String.valueOf(dataSnapshot.child("quantity").getValue());
final String time = String.valueOf(dataSnapshot.child("time").getValue());
final DatabaseReference progressRef = rootRef.child("Progress").child(key);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
shipment = String.valueOf(dataSnapshot.child("shipment").getValue());
firstMile = String.valueOf(dataSnapshot.child("firstMile").getValue());
distributor = String.valueOf(dataSnapshot.child("distributor").getValue());
}
if (shipment.equals("1") && firstMile.equals("2") && !distributor.equals("2")) {
counter++;
Information information = new Information(key, hotelName, location, quantity, time);
infoList.add(information);
distributorList.add(distributor);
try {
adapter = new DistributorItemAdapter(infoList, distributorList, getContext(), DistributorListFragment.this);
recyclerView.setAdapter(adapter);
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
} catch (NullPointerException e) {
Toast.makeText(getContext(), "No more Orders", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
} else {
shipment = "";
distributor = "";
firstMile = "";
}
if (counter == 0) {
emptyView.setVisibility(View.VISIBLE);
recyclerView.setAdapter(null);
} else
emptyView.setVisibility(View.GONE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("Database Error", databaseError.getMessage());
}
};
progressRef.addListenerForSingleValueEvent(eventListener);
countChilds++;
if (countChilds >= dataSnapshot.getChildrenCount()) {
if (pd.isShowing())
pd.dismiss();
if (!swipeRefresh.isEnabled())
swipeRefresh.setEnabled(true);
swipeRefresh.setRefreshing(false);
}
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
You should initialize your adapter where you initialize your recylerview and set adapter to recylcerView like the following.
//recyclerView = findViewById.....
infoList = new ArrayList<>();
distributorList = new ArrayList<>();
adapter = new DistributorItemAdapter(infoList, distributorList, getContext(), DistributorListFragment.this);
recyclerView.setAdapter(adapter);
Now modify your getData() like below.
public void getData() {
pd.setTitle("Loading Data");
pd.setMessage("Please Wait...");
pd.setCancelable(false);
pd.show();
infoList.clear();
distributorList.clear();
countChilds = 0;
counter = 0;
final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
final DatabaseReference hotelRef = rootRef.child("Orders");
hotelRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
final String key = String.valueOf(dataSnapshot.getKey());
final String hotelName = String.valueOf(dataSnapshot.child("hotelName").getValue());
final String location = String.valueOf(dataSnapshot.child("location").getValue());
final String quantity = String.valueOf(dataSnapshot.child("quantity").getValue());
final String time = String.valueOf(dataSnapshot.child("time").getValue());
final DatabaseReference progressRef = rootRef.child("Progress").child(key);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
shipment = String.valueOf(dataSnapshot.child("shipment").getValue());
firstMile = String.valueOf(dataSnapshot.child("firstMile").getValue());
distributor = String.valueOf(dataSnapshot.child("distributor").getValue());
}
if (shipment.equals("1") && firstMile.equals("2") && !distributor.equals("2")) {
counter++;
Information information = new Information(key, hotelName, location, quantity, time);
infoList.add(information);
distributorList.add(distributor);
// notify your adapter that data set is changed
adapter.notifyDatasetChanged();
} else {
shipment = "";
distributor = "";
firstMile = "";
}
if (counter == 0) {
emptyView.setVisibility(View.VISIBLE);
recyclerView.setAdapter(null);
} else
emptyView.setVisibility(View.GONE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("Database Error", databaseError.getMessage());
}
};
progressRef.addListenerForSingleValueEvent(eventListener);
countChilds++;
if (countChilds >= dataSnapshot.getChildrenCount()) {
if (pd.isShowing())
pd.dismiss();
if (!swipeRefresh.isEnabled())
swipeRefresh.setEnabled(true);
swipeRefresh.setRefreshing(false);
}
}
//....
});
}
I was trying to show user's profile in an activity. But when I try to do this, it only shows email. Name, photo, phone number is not showing. How can I show all the field of current user?I
I tried
getCurrentuser()
to get current user info and set them in the field. But it is not showing all the field.
SignUp.java
private EditText signUpnameId, signUpemailId,signUppasswordId,signUpPhoneId;
private Button signup_btn;
private TextView signUpSignIn;
private FirebaseAuth mAuth;
private ProgressBar progressBar;
private ImageView signUpimageView;
private static final String IMAGE_DIRECTORY = "/demonuts";
private int GALLERY = 1, CAMERA = 2;
private DatabaseReference mDatabase;
private Uri imageUri;
private String imageurl;
private static final int IMAGE_REQUEST = 1;
private StorageReference storageReference,imagename;
private StorageTask uploadTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
this.setTitle("Sign Up Here");
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progressbarId);
signUpnameId = findViewById(R.id.signUpnameId);
signUpemailId = findViewById(R.id.signUpemailId);
signup_btn = findViewById(R.id.signup_btn);
signUpSignIn = findViewById(R.id.signUpSignIn);
signUppasswordId = findViewById(R.id.signUppasswordId);
signUpimageView =findViewById(R.id.signUpImageId);
signUpPhoneId = findViewById(R.id.signUpphoneId);
mDatabase = FirebaseDatabase.getInstance().getReference("Users");
storageReference = FirebaseStorage.getInstance().getReference("usersImage");
signUpSignIn.setOnClickListener(this);
signup_btn.setOnClickListener(this);
signUpimageView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.signup_btn:
userRegister();
break;
case R.id.signUpSignIn:
Intent intent = new Intent(getApplicationContext(),LogIn.class);
startActivity(intent);
break;
case R.id.signUpImageId:
if(uploadTask != null && uploadTask.isInProgress())
{
Toast.makeText(getApplicationContext(),"Upload in process.",Toast.LENGTH_SHORT).show();
}else {
showPictureDialog();
}
}
}
private void showPictureDialog(){
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery" };
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
}
}
});
pictureDialog.show();
}
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(galleryIntent, GALLERY);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY && data != null && data.getData() != null ) {
imageUri = data.getData();
try {
Picasso.get().load(imageUri).into(signUpimageView);
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Failed!", Toast.LENGTH_SHORT).show();
}
}
}
private String getFileExtension(Uri uri){
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(contentResolver.getType(uri));
}
private void userRegister() {
final String name = signUpnameId.getText().toString();
final String email = signUpemailId.getText().toString().trim();
final String password = signUppasswordId.getText().toString().trim();
final String phoneNum = signUpPhoneId.getText().toString();
if(email.isEmpty())
{
signUpemailId.setError("Enter an email address");
signUpemailId.requestFocus();
return;
}
if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches())
{
signUpemailId.setError("Enter a valid email address");
signUpemailId.requestFocus();
return;
}
//checking the validity of the password
if(password.isEmpty())
{
signUppasswordId.setError("Enter a password");
signUppasswordId.requestFocus();
return;
}
if(password.length() < 6)
{
signUppasswordId.setError("Password is too short. Password Should be more than 6");
signUppasswordId.requestFocus();
return;
}
//checking the validity of the password
if(name.isEmpty())
{
signUpnameId.setError("Enter a Name");
signUpnameId.requestFocus();
return;
}
if(imageUri == null)
{
signUpSignIn.setError("Please select an image first");
}
progressBar.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if(task.isSuccessful())
{
mAuth.getCurrentUser().sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
final StorageReference Imagename = storageReference.child("image"+imageUri.getLastPathSegment());
imageurl = imageUri.toString();
Imagename.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(),"Place added Done!",Toast.LENGTH_SHORT).show();
Task<Uri> uriTask = taskSnapshot.getMetadata().getReference().getDownloadUrl();
while(!uriTask.isSuccessful());
Uri downloadUrl = uriTask.getResult();
UserInfo userInfo = new UserInfo(name,email,phoneNum,downloadUrl.toString());
String uploadId = mDatabase.push().getKey();
mDatabase.child(uploadId).setValue(userInfo);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
}
});
}
else
{
Toast.makeText(getApplicationContext(),"Error: "+task.getException().getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
}
else
{
if(task.getException() instanceof FirebaseAuthUserCollisionException)
{
Toast.makeText(getApplicationContext(),"Already registered",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),"Eroor: "+ task.getException(),Toast.LENGTH_SHORT).show();
}
}
}
});
}
Profile.Java
private ImageView profileImageview;
private TextView profilenameview,profileemailview, profilephoneview;
private Button profilesignoutbtn;
private FirebaseUser firebaseUser;
private FirebaseAuth mAuth;
private FirebaseDatabase firebaseDatabase;
private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
final FirebaseUser user = mAuth.getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
profileImageview = findViewById(R.id.profileImageView);
profileemailview = findViewById(R.id.profileemailview);
profilenameview = findViewById(R.id.profilenameview);
profilephoneview = findViewById(R.id.profilephoneview);
progressBar = findViewById(R.id.progressbarproId);
profilesignoutbtn = findViewById(R.id.profilesignout_btn);
profilesignoutbtn.setOnClickListener(this);
// Initialize Firebase Auth
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Image");
mAuth = FirebaseAuth.getInstance();
String userKey = user.getUid();
databaseReference.child("Profile");
databaseReference.child(userKey);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userName = dataSnapshot.child("users").getValue(String.class);
profilenameview.setText(user.getDisplayName());
profileemailview.setText(user.getEmail());
Picasso.get().load(user.getPhotoUrl()).into(profileImageview);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
UserInfo.java
public class UserInfo{
String name,email,phoneNum,imageurl;
public UserInfo(String name, String email, String phoneNum, String imageurl) {
this.name = name;
this.email = email;
this.phoneNum = phoneNum;
this.imageurl = imageurl;
}
public UserInfo(String name, String email, String phoneNum, Uri uri) {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public String getImageurl() {
return imageurl;
}
public void setImageurl(String imageurl) {
this.imageurl = imageurl;
}
}
Android studio is showing that
sendEmailVerification()
may produce NullPointerException. Besides
getReference()
and
getDownloadUrl()
also may produce NullPOinterException.How can I solve every issues and correctly get the expected output? Here is a screenshot of profile.
You aren't actually defining the name of the user ,
Use this in onCompleteListener method of firebase auth
new UserProfileChangeRequest.Builder()
.setDisplayName(nameUser)
.build();
I trying to store an image into firebase storage with getDownloadUri but it's already deprecated so I using uri to store image but I have an error in this line: String link = uri.toString;
And the error is cannot resolve symbol uri
private DatabaseReference Userdatabase;
private StorageReference storageReference;
private FirebaseAuth firebaseAuth;
private StorageTask mUploadTask;
private Uri imageUri;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
imageView = (ImageView) findViewById(R.id.imageView);
firebaseAuth = FirebaseAuth.getInstance();
Userdatabase = FirebaseDatabase.getInstance().getReference("User");
progressDialog = new ProgressDialog(Signup.this);
storageReference = FirebaseStorage.getInstance().getReference("Seller");
signupButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RegisterAccount();
}
});
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
public void selectImage() {
Intent photoPickerIntent = new Intent();
photoPickerIntent.setType("image/*");
photoPickerIntent.setAction(Intent.ACTION_PICK);
startActivityForResult(photoPickerIntent, PICK_IMAGE_REQUEST);
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
imageUri = data.getData();
Picasso.with(this).load(imageUri).into(imageView);
}
}
public void RegisterAccount() {
final String email = emailText.getText().toString();
final String username = nameText.getText().toString();
final String pass = passwordText.getText().toString();
if ((TextUtils.isEmpty(address))) {
addressText.setError("address is required");
addressText.requestFocus();
return;
}
AddUser(email, username, pass, phone, comfirmpass, address);
}
public void AddUser(final String UserEmail, final String Username, final String Password,
final String PhoneNumber, final String confirmPassword, final String Address) {
String email = UserEmail.replace(".", ",");
Userdatabase = FirebaseDatabase.getInstance().getReference("User").child(email);
Userdatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String value = dataSnapshot.getValue(String.class);
Toasty.warning(getApplicationContext(), "The Email you use already Exist !", Toast.LENGTH_SHORT, true).show();
return;
}
if (!dataSnapshot.exists()) {
if (imageUri != null) {
final StorageReference fileReference = storageReference.child(System.currentTimeMillis()
+ "." + getFileExtension(imageUri));
mUploadTask = fileReference.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri downloadUri) {
String link = uri.toString;
Toast.makeText(Signup.this, "Register successful", Toast.LENGTH_LONG).show();
final User user = new User(Address, confirmPassword, UserEmail, Password, PhoneNumber, Username,
link);
Userdatabase.setValue(user);
}
});
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
return;
}
});
firebaseAuth.createUserWithEmailAndPassword(UserEmail, Password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if (!task.isSuccessful()) {
Log.i(TAG, "Buyer FirebaseAuth Register : Fail");
Toasty.error(getApplicationContext(), "The Email you use already Exist !", Toast.LENGTH_SHORT, true).show();
} else {
Log.i(TAG, "Buyer FirebaseAuth Register : Success");
UserEmail.replace(".", ",");
final User user = new User(Address, confirmPassword, UserEmail, Password, PhoneNumber, Username,link);
Userdatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
Userdatabase.setValue(user);
Log.i(TAG, "FirebaseDatabase Add Buyer : Success");
Toasty.success(getApplicationContext(), "Register Complete", Toast.LENGTH_SHORT, true).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.w(TAG, "Database Error");
}
});
}
}
});
}
I had removed some of the code, so if you need more details pls comment below. your help is much appreciated
You are getting the following error:
cannot resolve symbol uri
Because you are calling toString() method on an object that does not exist. To solve this, please change the following line of code:
String link = uri.toString();
to
String link = downloadUri.toString();
I has an error in this line : final User user = new User(Address, confirmPassword, UserEmail, Password, PhoneNumber, Username,link);
and the error is "Cannot solve symbol link"
private DatabaseReference Userdatabase;
private StorageReference storageReference;
private FirebaseAuth firebaseAuth;
private StorageTask mUploadTask;
private Uri imageUri;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
imageView = (ImageView) findViewById(R.id.imageView);
firebaseAuth = FirebaseAuth.getInstance();
Userdatabase = FirebaseDatabase.getInstance().getReference("User");
progressDialog = new ProgressDialog(Signup.this);
storageReference = FirebaseStorage.getInstance().getReference("Seller");
signupButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RegisterAccount();
}
});
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
public void selectImage() {
Intent photoPickerIntent = new Intent();
photoPickerIntent.setType("image/*");
photoPickerIntent.setAction(Intent.ACTION_PICK);
startActivityForResult(photoPickerIntent, PICK_IMAGE_REQUEST);
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
imageUri = data.getData();
Picasso.with(this).load(imageUri).into(imageView);
}
}
public void RegisterAccount() {
final String email = emailText.getText().toString();
final String username = nameText.getText().toString();
if ((TextUtils.isEmpty(address))) {
addressText.setError("address is required");
addressText.requestFocus();
return;
}
AddUser(email, username, pass, phone, comfirmpass, address);
}
public void AddUser(final String UserEmail, final String Username, final String Password,
final String PhoneNumber, final String confirmPassword, final String Address) {
String email = UserEmail.replace(".", ",");
Userdatabase = FirebaseDatabase.getInstance().getReference("User").child(email);
Userdatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String value = dataSnapshot.getValue(String.class);
Log.i(TAG, "UserEmail : " + value + " Had Already Exist");
Toasty.warning(getApplicationContext(), "The Email you use already Exist !", Toast.LENGTH_SHORT, true).show();
return;
}
if (!dataSnapshot.exists()) {
if (imageUri != null) {
final StorageReference fileReference = storageReference.child(System.currentTimeMillis()
+ "." + getFileExtension(imageUri));
mUploadTask = fileReference.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri downloadUri) {
String link = downloadUri.toString();
Toast.makeText(Signup.this, "Register successful", Toast.LENGTH_LONG).show();
final User user = new User(Address, confirmPassword, UserEmail, Password, PhoneNumber, Username,
link);
Userdatabase.setValue(user);
}
});
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
return;
}
});
firebaseAuth.createUserWithEmailAndPassword(UserEmail, Password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if (!task.isSuccessful()) {
Log.i(TAG, "Buyer FirebaseAuth Register : Fail");
Toasty.error(getApplicationContext(), "The Email you use already Exist !", Toast.LENGTH_SHORT, true).show();
} else {
Log.i(TAG, "Buyer FirebaseAuth Register : Success");
UserEmail.replace(".", ",");
final User user = new User(Address, confirmPassword, UserEmail, Password, PhoneNumber, Username,link);
Userdatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
Userdatabase.setValue(user);
Log.i(TAG, "FirebaseDatabase Add Buyer : Success");
Toasty.success(getApplicationContext(), "Register Complete", Toast.LENGTH_SHORT, true).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.w(TAG, "Database Error");
}
});
}
}
});
}
I had removed some of the codes if you need more details pls leave a comment below. Anyone can help with this? your help is much appreciated
Declare link at the start of your class with the other variables, and then set link when you need it. It can't resolve symbol link because it doesn't exist in the context youre calling it.
private DatabaseReference Userdatabase;
private StorageReference storageReference;
private FirebaseAuth firebaseAuth;
private String link;
private StorageTask mUploadTask;
private Uri imageUri;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
imageView = (ImageView) findViewById(R.id.imageView);
firebaseAuth = FirebaseAuth.getInstance();
Userdatabase = FirebaseDatabase.getInstance().getReference("User");
progressDialog = new ProgressDialog(Signup.this);
storageReference = FirebaseStorage.getInstance().getReference("Seller");
signupButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RegisterAccount();
}
});
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
public void selectImage() {
Intent photoPickerIntent = new Intent();
photoPickerIntent.setType("image/*");
photoPickerIntent.setAction(Intent.ACTION_PICK);
startActivityForResult(photoPickerIntent, PICK_IMAGE_REQUEST);
}
private String getFileExtension(Uri uri) {
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
imageUri = data.getData();
Picasso.with(this).load(imageUri).into(imageView);
}
}
public void RegisterAccount() {
final String email = emailText.getText().toString();
final String username = nameText.getText().toString();
if ((TextUtils.isEmpty(address))) {
addressText.setError("address is required");
addressText.requestFocus();
return;
}
AddUser(email, username, pass, phone, comfirmpass, address);
}
public void AddUser(final String UserEmail, final String Username, final String Password,
final String PhoneNumber, final String confirmPassword, final String Address) {
String email = UserEmail.replace(".", ",");
Userdatabase = FirebaseDatabase.getInstance().getReference("User").child(email);
Userdatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
String value = dataSnapshot.getValue(String.class);
Log.i(TAG, "UserEmail : " + value + " Had Already Exist");
Toasty.warning(getApplicationContext(), "The Email you use already Exist !", Toast.LENGTH_SHORT, true).show();
return;
}
if (!dataSnapshot.exists()) {
if (imageUri != null) {
final StorageReference fileReference = storageReference.child(System.currentTimeMillis()
+ "." + getFileExtension(imageUri));
mUploadTask = fileReference.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri downloadUri) {
link = downloadUri.toString();
Toast.makeText(Signup.this, "Register successful", Toast.LENGTH_LONG).show();
final User user = new User(Address, confirmPassword, UserEmail, Password, PhoneNumber, Username,
link);
Userdatabase.setValue(user);
}
});
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
return;
}
});
firebaseAuth.createUserWithEmailAndPassword(UserEmail, Password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if (!task.isSuccessful()) {
Log.i(TAG, "Buyer FirebaseAuth Register : Fail");
Toasty.error(getApplicationContext(), "The Email you use already Exist !", Toast.LENGTH_SHORT, true).show();
} else {
Log.i(TAG, "Buyer FirebaseAuth Register : Success");
UserEmail.replace(".", ",");
final User user = new User(Address, confirmPassword, UserEmail, Password, PhoneNumber, Username,link);
Userdatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
Userdatabase.setValue(user);
Log.i(TAG, "FirebaseDatabase Add Buyer : Success");
Toasty.success(getApplicationContext(), "Register Complete", Toast.LENGTH_SHORT, true).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.w(TAG, "Database Error");
}
});
}
}
});
}
You are getting that error, because the declaration of your:
String link = downloadUri.toString();
Is out of the scope. You cannot simply use the String link declared in addsuccesslistener, in your onComplete() method because is a total different scope. The String link can only be see,n in the scope where it have been declared. Beside that, both methods have an asynchronous behavior. So even if you make that variable, a global variable, it won't solve the problem. The simplest fix I can see, would be to use in your onComplete() method, the link as an empty String:
final User user = new User(
Address,
confirmPassword,
UserEmail,
Password,
PhoneNumber,
Username,
"" //empty String
);
And update accordingly, when you get it.
See also here more informations.