Hello I created an android application which receives automatic push notifications and store them in the main activity... Basically I am storing the notifications in an edit text just for testing and it is working... How can I get the messages in a listview instead of an edit text? and can I make a table and display the date and time in a column and the message in another column next to it?
My code for storing in edittext is the following:
final FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference myRef = database.getReference("Fall_Detection_Status");
final DatabaseReference myRef1 = database.getReference("Fall_Detection_Status1");
final DatabaseReference myRef2 = database.getReference("Seizure");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
val = dataSnapshot.getValue(Long.class);
if(val.longValue() == 1 && val1.longValue() == 1) {
Date currentTime = Calendar.getInstance().getTime();
writeToFile(currentTime.toString() + "\n" + " Fall Detected" + "\n", getApplicationContext());
result.setText("");
result.setText(readFromFile(getApplicationContext()));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
myRef1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
val1 = dataSnapshot.getValue(Long.class);
if(val.longValue() == 1 && val1.longValue() == 1) {
Date currentTime = Calendar.getInstance().getTime();
writeToFile(currentTime.toString() + "\n" + " Fall Detected" + "\n", getApplicationContext());
result.setText("");
result.setText(readFromFile(getApplicationContext()));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
myRef2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Toast.makeText(getApplicationContext(),"This is a test!",Toast.LENGTH_LONG).show();
val2 = dataSnapshot.getValue(Long.class);
if(val2.longValue() == 1){
Date currentTime = Calendar.getInstance().getTime();
writeToFile(currentTime.toString() + "\n" + " Seizure Detected" + "\n", getApplicationContext());
result.setText("");
result.setText(readFromFile(getApplicationContext()));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
result.setText("");
result.setText(readFromFile(getApplicationContext()));
myRef.setValue(0);
myRef1.setValue(0);
myRef2.setValue(0);
private String readFromFile(Context context)
{
StringBuilder total = new StringBuilder();
BufferedReader r = null;
try {
r = new BufferedReader(new InputStreamReader(context.openFileInput("events.txt")));
String line;
while ((line = r.readLine()) != null) {
total.append(line).append('\n');
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return total.toString();
}
private void writeToFile(String data,Context context) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("events.txt", Context.MODE_APPEND));
outputStreamWriter.append(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
Take your push notification value in ArrayList and implement in recycler feature.
Notify the recycler adapter when you have new push message.
Recycler implementation example
Just read sqlLite database tutorial of android.
Android Database Tutorial
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 trying to get a list of my last active users in my app. I am storing the UIDs of them as a string in my database it's as follow in the database:
lastActiveUsers:uid1 uid2 ... etc.
Now I need to show a list of the users with the UIds in this string but when using nested listener I don't know how to do that this is my code :
this is my code :
public void getStudents() {
if (!list.isEmpty()) {
list.clear();
}
lastActiveUsersReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String lastActiveUsers = (String) dataSnapshot.getValue();
final String[] lastActiveUsersArray = lastActiveUsers.split(" ");
for(final String userId : lastActiveUsersArray){
usersReference.orderByKey().equalTo(userId).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String localCurrentUserUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
User user = new User();
String points = "";
boolean admin = false, online = false;
String name = (String) dataSnapshot1.child("userName").getValue();
String email = (String) dataSnapshot1.child("userEmail").getValue();
String uid = dataSnapshot1.getKey();
if (dataSnapshot1.child("points").getValue() != null)
points = dataSnapshot1.child("points").getValue().toString();
String imageUrl = (String) dataSnapshot1.child("userImage").getValue();
String userType = (String) dataSnapshot1.child("userType").getValue();
if (dataSnapshot1.child("admin").getValue() != null)
admin = (boolean) dataSnapshot1.child("admin").getValue();
if (dataSnapshot1.child("online").getValue() != null) {
online = (boolean) dataSnapshot1.child("online").getValue();
/*if(online)
onlineUsersIndexes.add(list.size());//TODO : try to add this after solving its problem*/
}
int pointsInt;
try{
pointsInt = Integer.parseInt(points);
}
catch (Exception ex){
Log.v("pointsException", "exception is : " + ex);
pointsInt = 0;
}
Log.v("Sizee", "array size : " + lastActiveUsersArray.length
+ " , userId : " + userId + " , array : " + lastActiveUsersArray.toString());
if (userType.equals("طالب") && !uid.equals(localCurrentUserUid) && !inList(userId) && !online && name != null) {//TODO : think about allowing challenges against teachers and others and ask my friends about thier opinions in that
user.setAdmin(admin);
user.setOnline(online);
user.setName(name);
user.setPoints(pointsInt);
user.setImageUrl(imageUrl);
user.setEmail(email);
user.setUid(uid);
list.add(user);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Toast.makeText(ChallengersActivity.this, "list size is : " + list.size(), Toast.LENGTH_SHORT).show();
recyclerAdapter.notifyDataSetChanged();
if (progressBar.getVisibility() != View.GONE)
progressBar.setVisibility(View.GONE);
if (swipeRefreshLayout.isRefreshing()) {
swipeRefreshLayout.setRefreshing(false);
}
if (list.size() == 0) {
noStudentsTv.setVisibility(View.VISIBLE);
noInternetConnectionText.setVisibility(View.GONE);
} else {
noStudentsTv.setVisibility(View.INVISIBLE);
noInternetConnectionText.setVisibility(View.GONE);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Hello I am trying to search data from firebase database. But I don't see there any option for search data from firebase. In my firebase database, there are address, city and mobile number that are present. I want to search data from that if I enter mobile number last digit. I want to get result that mobile number.
Here is my code
floating_search_view_recruiter = (FloatingSearchView) findViewById(R.id.floating_search_view_recruiter);
floating_search_view_recruiter.setSearchHint("Search Recruiter..");
floating_search_view_recruiter.attachNavigationDrawerToMenuButton(drawer);
floating_search_view_recruiter.setOnMenuItemClickListener(new FloatingSearchView.OnMenuItemClickListener() {
#Override
public void onActionMenuItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_filter) {
aleartDialogFilter();
}
}
});
fab_recyclerView.setVisibility(View.GONE);
floating_search_view_recruiter.setOnQueryChangeListener(new FloatingSearchView.OnQueryChangeListener() {
#Override
public void onSearchTextChanged(String oldQuery, String newQuery) {
//recruiterAdapter.getFilter().filter(newQuery);
mRef.orderByChild("city")
.startAt(newQuery)
.endAt(newQuery + "\uf8ff");
mRef.child("city").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
Please refer this github repository for more examples
enter link description here
mDatabase = FirebaseDatabase.getInstance().getReference().child("appointment");
Query query = mDatabase.orderByChild("patient").equalTo(restoredText.toString());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot != null || dataSnapshot.getChildrenCount() > 0) {
collectPhoneNumbers((Map<String, Object>) dataSnapshot.getValue());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Failed to read value
Toast.makeText(getApplicationContext(), "Failed to read value." + databaseError.toException(), Toast.LENGTH_LONG).show();
}
});
private void collectPhoneNumbers(Map<String, Object> users) {
if (users != null && !users.isEmpty()) {
contacts.clear();
contacts.add(new Appointment("<b>Date</b>", "<b>Time</b>", "<b>Doctor Name</b>", "<b>Patient Name</b>"));
//iterate through each user, ignoring their UID
for (Map.Entry<String, Object> entry : users.entrySet()) {
//Get user map
Map singleUser = (Map) entry.getValue();
//Get phone field and append to list
String date = (String) singleUser.get("date");
String time = (String) singleUser.get("time");
String doctor = (String) singleUser.get("doctor");
String patient = (String) singleUser.get("patient");
contacts.add(new Appointment(date, time, doctor, patient));
// Toast.makeText(getApplicationContext(), "Date: " + date + ", Time:" + time + ", Doctor:" + doctor + ", Patient:" + patient, Toast.LENGTH_LONG).show();
adapter.notifyDataSetChanged();
}
}
}
Hi I was trying firebase with , My server has around 300 records which is getting synced with my app in 3 to four minutes in single, single way
cant it be like get record in set of 50 or something ??
If user is coming online after very long time then also I need this batching.
If user is installing app first time then also i need to download bulk record from firebase database
I am using
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.e(TAG, "addListenerForSingleValueEvent:onDataChange" + dataSnapshot.getValue());
reference.removeEventListener(valueEventListener);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "addListenerForSingleValueEvent:onCancelled" + databaseError.getMessage());
}
};
and
public class DBService extends Service {
private static final String TAG = DBService.class.getName();
private StartApplication application;
private ObjectMapper objectMapper;
#Override
public void onCreate() {
super.onCreate();
application = ((StartApplication) getApplication());
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference reference = database.getReference();
objectMapper = new ObjectMapper();
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
try {
String json = objectMapper.writeValueAsString(dataSnapshot.getValue());
Job job = objectMapper.readValue(json, Job.class);
ContentValues values = ContentValuesParser.parseJobs(job);
Uri uri = getContentResolver().insert(TableContract.JobsEntry.CONTENT_URI, values);
Log.d(TAG, "child add id " + job.getId() + " Uri " + uri.getEncodedPath());
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
//Uri uri = getContentResolver().insert(TableContract.JobsEntry.CONTENT_URI, values);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
try {
String json = objectMapper.writeValueAsString(dataSnapshot.getValue());
Job job = objectMapper.readValue(json, Job.class);
ContentValues values = ContentValuesParser.parseJobs(job);
Uri uri = getContentResolver().insert(TableContract.JobsEntry.CONTENT_URI, values);
Log.d(TAG, "child changed id " + job.getId() + " Uri " + uri.getEncodedPath());
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
reference.child("jobs").addChildEventListener(childEventListener);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}}
Have you tried Querying data?
Query queryRef = ref.orderByChild("weight").limitToLast(50);
//This will fetch the last 50 children.
queryRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot snapshot, String previousChild) {
System.out.println(snapshot.getKey());
}
This is my Service class which is calling to all listener
public class DBService extends Service {
private static final String TAG = DBService.class.getName();
private DatabaseReference reference;
private static final String FIREBASE_EMAIL = "xxxxxxx#workindia.in";
private static final String FIREBASE_PASSWORD = "xxxxxx";
#Override
public void onCreate() {
super.onCreate();
FirebaseDatabase database = FirebaseDatabase.getInstance();
reference = database.getReference();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
FirebaseAuth auth = ((StartApplication) getApplication()).getAuth();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user == null) {
String email = ObjectGraph.getEmployeeProfile().getEmail();
String password = ObjectGraph.getEmployeeProfile().getMobile_no();
if (password != null && !password.trim().isEmpty()) {
if (email == null || email.trim().isEmpty()) {
email = password + FIREBASE_EMAIL;
}
signIn(auth, email, FIREBASE_PASSWORD);
}
} else {
addListeners();
}
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
addListeners();
return null;
}
private void signIn(final FirebaseAuth auth, final String email, final String password) {
Log.i(TAG, "Login");
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
boolean isResetTimeStamp = true;
setTimeStamp(isResetTimeStamp);
addListeners();
} else {
register(auth, email, password);
}
}
});
FirebaseAuth.AuthStateListener authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
Log.e(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
Log.e(TAG, "onAuthStateChanged:signed_out");
}
}
};
auth.addAuthStateListener(authListener);
}
private void addListeners() {
EmployeeProfile profile = ObjectGraph.getEmployeeProfile();
if (profile != null && profile.getMobile_no() != null && !profile.getMobile_no().trim().isEmpty()) {
reference.child(AppConstants.WORKINDIA_USERS_LAST_TIME).child(profile.getMobile_no().trim()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, Object> child = (Map<String, Object>) dataSnapshot.getValue();
Log.e(TAG, "DATA " + child);
if (child == null) {
/*Query Listener Other listener*/
Query recentPostsQuery = reference.child(AppConstants.WORKINDIA_JOB_NODE).limitToFirst(1000);//.orderByChild("timestamp");
recentPostsQuery.addValueEventListener(jobBulKDownloadListener);
} else {
long lastSyncTime = (Long) child.get(AppConstants.TIMESTAMP);
Log.e(TAG, "DATA " + lastSyncTime);
/*Query Listener Other listener*/
Query recentPostsQuery = reference.child(AppConstants.WORKINDIA_JOB_NODE)
.orderByChild(AppConstants.TIMESTAMP)
.startAt(lastSyncTime)
.limitToFirst(1000);//.orderByChild("timestamp");
recentPostsQuery.addValueEventListener(jobBulKDownloadListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, databaseError.getMessage(), databaseError.toException());
}
});
}
}
private void register(final FirebaseAuth auth, final String email, final String password) {
Log.e(TAG, "register");
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.e(TAG, "register true");
signIn(auth, email, password);
} else {
Log.e(TAG, "register fail");
}
}
});
}
ValueEventListener jobBulKDownloadListener = new ValueEventListener() {
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
Toast.makeText(getApplicationContext(), "jobBulKDownloadListener+ onDataChange", Toast.LENGTH_SHORT).show();
new Thread(new Runnable() {
#Override
public void run() {
try {
if (dataSnapshot != null) {
long time = System.currentTimeMillis();
Log.d(TAG, "Start Process : " + (System.currentTimeMillis() - time) / 1000 + " Seconds");
List<Job> jobs = new ArrayList<Job>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
WrapperJob job1 = snapshot.getValue(WrapperJob.class);
Job job = job1.getData();
jobs.add(job);
}
if (jobs.size() > 0) {
parseJobs(jobs);
}
Log.d(TAG, "After Process : " + (System.currentTimeMillis() - time) / 1000 + " Seconds");
}
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
Crashlytics.logException(e);
}
}
}).start();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, databaseError.getMessage(), databaseError.toException());
}
};
private void parseJobs(List<Job> jobs) {
/* Job Operations*/
}
}
Why it is getting hanged ?? I have kept almost everything on background thread
This may not be the problem, but in your jobBulKDownloadListener it's probably safer to operate on the DataSnapshot on the main thread instead of your worker thread. You could refactor it like this:
ValueEventListener jobBulKDownloadListener = new ValueEventListener() {
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
Toast.makeText(getApplicationContext(), "jobBulKDownloadListener+ onDataChange", Toast.LENGTH_SHORT).show();
if (dataSnapshot != null) {
final List<Job> jobs = new ArrayList<Job>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
WrapperJob job1 = snapshot.getValue(WrapperJob.class);
Job job = job1.getData();
jobs.add(job);
}
if (jobs.size() > 0) {
new Thread(new Runnable() {
#Override
public void run() {
try {
long time = System.currentTimeMillis();
Log.d(TAG, "Start Process : " + (System.currentTimeMillis() - time) / 1000 + " Seconds");
parseJobs(jobs);
Log.d(TAG, "After Process : " + (System.currentTimeMillis() - time) / 1000 + " Seconds");
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
Crashlytics.logException(e);
}
}
}).start();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, databaseError.getMessage(), databaseError.toException());
}
};