How to attach adapter in fragment after data synced in service - java

I have written my GeoQuery Code in the Service which also implements location service. I want the adapter to be synchronised in service class and after the data has been loaded I want it to be attached to RecyclerView in the Fragment here is the code I am implementing in the Service.
private void startGeoQuery() {
query = geoFire.queryAtLocation(center, 2);
Log.d(TAG, "center: " + center.toString() + ", radius: " + 2);
query.addGeoQueryEventListener(new GeoQueryEventListener() {
#Override
public void onKeyEntered(String key, GeoLocation location) {
Log.d(TAG, "Key " + key + " entered the search area at [" + location.latitude + "," + location.longitude + "]");
DatabaseReference tempRef = mFirebaseRef.child(key);
tempRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
// I add the deal only if it doesn't exist already in the adapter
String key = snapshot.getKey();
if (!mAdapter.exists(key)) {
Log.d(TAG, "item added " + key);
mAdapter.addSingle(snapshot);
mAdapter.notifyDataSetChanged();
} else {
//...otherwise I will update the record
Log.d(TAG, "item updated: " + key);
mAdapter.update(snapshot, key);
mAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onKeyExited(String key) {
Log.d(TAG, "deal " + key + " is no longer in the search area");
mAdapter.remove(key);
isListEmpty(); // Method from the Fragment
}
#Override
public void onKeyMoved(String key, GeoLocation location) {
Log.d(TAG, String.format("Key " + key + " moved within the search area to [%f,%f]", location.latitude, location.longitude));
DatabaseReference tempRef = mFirebaseRef.child(key);
tempRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
// I add the deal only if it doesn't exist already in the adapter
String key = snapshot.getKey();
if (!mAdapter.exists(key)) {
Log.d(TAG, "item added " + key);
mAdapter.addSingle(snapshot);
mAdapter.notifyDataSetChanged();
} else {
//...otherwise I will update the record
Log.d(TAG, "item updated: " + key);
mAdapter.update(snapshot, key);
mAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onGeoQueryReady() {
Log.d(TAG, "All initial data has been loaded and events have been fired!");
isListEmpty(); //Method from the Fragment
mActiveGeoQuery = true;
}
#Override
public void onGeoQueryError(DatabaseError error) {
Log.e(TAG, "There was an error with this query: " + error);
mActiveGeoQuery = false;
}
});
bindRecyclerView(); //Method from the Fragment
}
This is the code in the Fragment Class
public void bindRecyclerView() {
mRecyclerView.setAdapter(mAdapter);
}
private void isListEmpty() {
if (mAdapter.getItemCount() == 0) {
filterList(key);
}
}
public void filterList(String query) {
if (query.equals("")) {
mAdapter = new FirebasePostsQueryAdapter(mFirebaseRef.limitToFirst(20), R.layout.geo_feeds_items, getActivity(), PostViewHolder.class);
} else {
mAdapter = new FirebasePostsQueryAdapter(mFirebaseRef.orderByValue().startAt(query), R.layout.geo_feeds_items, getActivity(), PostViewHolder.class);
}
bindRecyclerView();
}

Related

FIrebase Realtime Database Reference.addValueEventListener is not working when I call at the first time

I would like to get children counts and set it as my key, so that the database would be read easily.
It would look like this.
When I click the button to insert a new data to database, reference2.child(Rname).addValueEventListener method is not work.
The childpath(ordercnt[0]) in reference2.child(Rname).child(ordercnt[0]).child(Integer.toString(i)).setValue(order); is null and cause crashed.
Cart_submitBtn = view.findViewById(R.id.Cart_submitBtn);
Cart_submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String Rname = selected.get(0).getRName();
reference2.child(Rname).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
ordercnt[0] = Long.toString(snapshot.getChildrenCount());
}
else{ ordercnt[0] = "0"; }
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
reference1.child(mAuth.getCurrentUser().getUid()).get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
User user = task.getResult().getValue(User.class);
if(user != null){
for(int i = 0; i < selected.size(); i++) {
String order = "";
order += "餐點名稱: " + selected.get(i).getsName() + " ";
order += selected.get(i).getsCnt() + "份";
order += selected.get(i).getsPrice() + "元 ";
reference2.child(Rname).child(ordercnt[0]).child(Integer.toString(i)).setValue(order);
}
}
}
});
}
});
Error:
I think it is null because you do for reference1 outside the method onDataChange from reference2.
Put your reference1 below the else{ ordercnt[0] = "0"; }
reference2.child(Rname).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
ordercnt[0] = Long.toString(snapshot.getChildrenCount());
}
else{ ordercnt[0] = "0"; }
//Put your reference1 at here
reference1....
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});

How to add image list in Firebase?

I want to upload image list in firebase but in the firebase upload success listener doesn't add image list on OnSuccessListener.
Tried
I add string value outside of the add onSuccessListener class it works and i tried to log the url it works too.But it doesn't add the string value in the arrayList in the OnSuccessListener.
Thank you for the help.
Main code
public void UploadImage() {
if (isUserSelected != null) {
progressDialog.setTitle("Image is Uploading...");
Log.d(TAG, "UploadImage: uploading");
progressDialog.show();
Log.d(TAG, "UploadImage: after progress bar");
for (int i = 0; i < multipleFileUploads.size(); i++) {
Log.d(TAG, "UploadImage: " + i);
final StorageReference storageReference2 = storageReference.child(System.currentTimeMillis() + "." + GetFileExtension(multipleFileUploads.get(i)));
storageReference2.putFile(multipleFileUploads.get(i))
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Log.d(TAG, "onSuccess: ");
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Image Uploaded Successfully ", Toast.LENGTH_LONG).show();
storageReference2.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Log.d(TAG, "onSuccess: uri " + uri.toString());
imagelist.add(uri.toString());
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: " + e.getMessage());
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
Log.d(TAG, "onProgress: " + taskSnapshot.getBytesTransferred());
Log.d(TAG, "onProgress: " + taskSnapshot.getTotalByteCount());
}
}).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
Log.d(TAG, "onComplete: " + task.getException());
}
});
}
imageList.add("custom list");
uploadinfo imageUploadInfo = new uploadinfo(txtdata.getText().toString(), txtData1.getText().toString(), imageList.toString());
String ImageUploadId = databaseReference.push().getKey();
databaseReference.child(ImageUploadId).setValue(imageUploadInfo);
} else {
Toast.makeText(uploadimg1.this, "Please Select Image or Add Image Name", Toast.LENGTH_LONG).show();
}
POJO Code for Firebase
public class uploadinfo {
public String imageName;
public String imageName1;
public String imageListString;
public uploadinfo(String imageName, String imageName1, String imageListString) {
this.imageName = imageName;
this.imageName1 = imageName1;
this.imageListString = imageListString;
}
public String getImageName() {
return imageName;
}
public void setImageName(String imageName) {
this.imageName = imageName;
}
public String getImageName1() {
return imageName1;
}
public void setImageName1(String imageName1) {
this.imageName1 = imageName1;
}
public String getImageListString() {
return imageListString;
}
public void setImageListString(String imageListString) {
this.imageListString = imageListString;
}
}
In Firebase
The problem might be in your model. In firebase the order goes imageListString, imageName, imageName1. But in model in constructor you got String imageName, String imageName1, String imageListString. At the same time im not sure how you generate the list which you create BEFORE send it to Firebase.
You can try this method
UploadTask uploadTask = storageReference2.putFile(multipleFileUploads.get(i));
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();
}
// Continue with the task to get the download URL
return ref.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
imagelist.add(downloadUri.toString());
} else {
// Handle failures
// ...
}
}
});

Displaying only service name NSD network service discovery Android

I have this question again about NSD, this time I would like to ask ask if anybody know how to display only service name without all the details like port, host, service type.So far I managed to display all services using ArrayList and NsdServiceInfo object which displays all details about service as I mentioned before, but in my case I want to display only service name.
If you have any ideas, you are more than welcome to share with me
private String SERVICE_TYPE = "_lala._tcp.";
private InetAddress hostAddress;
private int hostPort;
private NsdManager mNsdManager;
NsdServiceInfo mService;
private WebView mWebView;
ArrayList<NsdServiceInfo> services;
ArrayAdapter<NsdServiceInfo> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Getting toolbar by id
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//disabling default title text
getSupportActionBar().setDisplayShowTitleEnabled(false);
//NSD stuff
mNsdManager = (NsdManager) getSystemService(Context.NSD_SERVICE);
mNsdManager.discoverServices(SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);
//Creating the arrayList and arrayAdapter to store services
services = new ArrayList<>();
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, services);
ListView listView = findViewById(R.id.ListViewServices);
listView.setAdapter(adapter);
//Creating onClick listener for the chosen service and trying to resolve it
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Object serviceObj = adapterView.getItemAtPosition(i);
NsdServiceInfo selectedService = (NsdServiceInfo) serviceObj;
//mNsdManager.stopServiceDiscovery(mDiscoveryListener);
mNsdManager.resolveService(selectedService, mResolveListener);
}
});
}
// Each time create new discovery listener for discovery methods onServicefound.
NsdManager.DiscoveryListener mDiscoveryListener = new NsdManager.DiscoveryListener() {
#Override
public void onStartDiscoveryFailed(String serviceType, int errorCode) {
Log.e("TAG", "DiscoveryFailed: Error code: " + errorCode);
mNsdManager.stopServiceDiscovery(this);
}
#Override
public void onStopDiscoveryFailed(String serviceType, int errorCode) {
Log.e("TAG", "Discovery failed : Error code: " + errorCode);
}
#Override
public void onDiscoveryStarted(String regType) {
Log.d("TAG", "Service discovery started");
}
#Override
public void onDiscoveryStopped(String serviceType) {
Log.i("TAG", "Discovery stopped: " + serviceType);
}
// When service is found add it to the array. Log d is for debugging purposes.
#Override
public void onServiceFound(NsdServiceInfo serviceInfo) {
Log.d("TAG", "Service discovery success : " + serviceInfo);
Log.d("TAG", "Host = " + serviceInfo.getServiceName());
Log.d("TAG", "Port = " + serviceInfo.getPort());
services.add(serviceInfo);
//Notifying adapter about change in UI thread because it informs view about data change.
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
}
});
}
//When service connection is lost to avoid duplicating we create new serviceToRemove object and check if that object is equals to current service,
// if it yes wre remove the service from an array and inform adapter about the change.
#Override
public void onServiceLost(NsdServiceInfo nsdServiceInfo) {
Log.d("TAG", "Service lost " + nsdServiceInfo);
NsdServiceInfo serviceToRemove = new NsdServiceInfo();
for (NsdServiceInfo currentService : services) {
if (currentService.getHost() == nsdServiceInfo.getHost() && currentService.getPort() == currentService.getPort() && currentService.getServiceName() == currentService.getServiceName()) {
serviceToRemove = currentService;
}
}
if (serviceToRemove != null) {
services.remove(serviceToRemove);
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
}
});
}
Log.d("TAG", "Xd" + services);
}
//}
};
//Creating new Resolve listener each time when user chooses the service. If the connection was made we launch web view activity with the webpage.
NsdManager.ResolveListener mResolveListener = new NsdManager.ResolveListener() {
#Override
public void onResolveFailed(NsdServiceInfo nsdServiceInfo, int errorCode) {
Log.e("TAG", "Resolved failed " + errorCode);
Log.e("TAG", "Service = " + nsdServiceInfo);
}
#Override
public void onServiceResolved(NsdServiceInfo nsdServiceInfo) {
Log.d("TAG", "bbz" + nsdServiceInfo);
runOnUiThread(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(MainActivity.this, WebViewActivity.class);
startActivity(intent);
}
});
Log.d("TAG", "Resolve Succeeded " + nsdServiceInfo);
if (nsdServiceInfo.getServiceType().equals(SERVICE_TYPE)) {
Log.d("TAG", "Same IP");
return;
}
hostPort = nsdServiceInfo.getPort();
hostAddress = nsdServiceInfo.getHost();
}
};
// NsdHelper's tearDown method
public void tearDown() {
mNsdManager.stopServiceDiscovery(mDiscoveryListener);
}
}

Can't get heart rate data from google fit API with smartband 2

I'm trying to use google Fit API to get heartrate from sony smartband2. Problem is, I don't get any readings(i.e. onDataPoint method is not called). Heart Rate sensor is being found properly, whole code also is working properly if I try to look for step data.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
authInProgress = savedInstanceState.getBoolean(AUTH_PENDING);
}
mApiClient = new GoogleApiClient.Builder(this)
.addApi(Fitness.SENSORS_API)
.addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ))
.addScope(new Scope(Scopes.FITNESS_BODY_READ))
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
protected void onStart() {
super.onStart();
mApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
final DataSourcesRequest dataSourceRequest = new DataSourcesRequest.Builder()
.setDataTypes(DataType.TYPE_HEART_RATE_BPM)
.setDataSourceTypes(DataSource.TYPE_RAW)
.build();
Fitness.SensorsApi.findDataSources(mApiClient, dataSourceRequest)
.setResultCallback(new ResultCallback<DataSourcesResult>() {
#Override
public void onResult(DataSourcesResult dataSourcesResult) {
for(DataSource dataSource : dataSourcesResult.getDataSources())
{
Log.i(TAG, "Data source found: " + dataSource.toString());
Log.i(TAG, "Data Source type: " + dataSource.getDataType().getName());
registerFitnessDataListener(dataSource, DataType.TYPE_HEART_RATE_BPM);
}
}
});
// dataSourceRequest = new DataSourcesRequest.Builder()
// .setDataTypes(DataType.TYPE_STEP_COUNT_CUMULATIVE)
// .setDataSourceTypes(DataSource.TYPE_RAW)
// .build();
// Fitness.SensorsApi.findDataSources(mApiClient, dataSourceRequest)
// .setResultCallback(dataSourcesResultCallback);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (!authInProgress) {
try {
authInProgress = true;
connectionResult.startResolutionForResult(MainActivity.this, REQUEST_OAUTH);
} catch (IntentSender.SendIntentException e) {
}
} else {
Log.e("GoogleFit", "authInProgress");
}
}
#Override
public void onDataPoint(DataPoint dataPoint) {
for (final Field field : dataPoint.getDataType().getFields()) {
final Value value = dataPoint.getValue(field);
Log.i("DATASOURCE", field.getName());
Log.i("DATASOURCE", value.toString());
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView tv = (TextView) findViewById(R.id.tv1);
tv.setText("Field: " + field.getName() + " Value: " + value);
Toast.makeText(getApplicationContext(), "Field: " + field.getName() + " Value: " + value, Toast.LENGTH_SHORT).show();
}
});
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_OAUTH) {
authInProgress = false;
if (resultCode == RESULT_OK) {
if (!mApiClient.isConnecting() && !mApiClient.isConnected()) {
mApiClient.connect();
} else {
TextView tv = (TextView) findViewById(R.id.tv1);
tv.setText("connected");
}
} else if (resultCode == RESULT_CANCELED) {
Log.e("GoogleFit", "Result_Canceled");
}
} else {
Log.e("GoogleFit", "Request not OAUTH");
}
}
private void registerFitnessDataListener(final DataSource dataSource, DataType dataType) {
SensorRequest request = new SensorRequest.Builder()
.setDataSource(dataSource)
.setDataType(dataType)
.setSamplingRate(2, TimeUnit.SECONDS)
.build();
Fitness.SensorsApi.add(mApiClient, request, this)
.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (!status.isSuccess()) {
Log.e("DATASOURCES", "register " + dataSource.getName() + " failed");
} else {
Log.i("DATASOURCES", "register " + dataSource.getName() + " succeed");
}
}
});
}
}
Do You have any ideas why i can't get the data?
Ok, After I found that this code was working on someone's phone, I found out that You need to enable SmartBand2 application option to share data to Google Fit. For some reason smartband 2 can't connect to Google Fit independently from it's application.

How to retrieve child data in Firebase by using "PUSH" without an any encryption format

I am building a messenger app in android and I am trying to retrieve data from Firebase in my android application. But when I do I get the full tree in my screen. I want to access the child directly. Is there a way to get only the value I want?
retr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Attach an listener to read the data at our posts reference
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
totalmsg[0] =snapshot.getValue().toString();
emultiview.setText(totalmsg[0].toString());
}
#Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
}
});
I want to retrive hello from this in Firebase. The problem i am facing here is the encryption data. Is there any way I can retrieve that? And I am not able to append data without using push(),is there any other alternative to push()?
{
"chat" : {
"-JZvOzp0L1ccuBt2TVN7" : {
"author" : "JavaUser21221",
"message" : "hello "
},
"-JZvPneW5et0_EVRvL5g" : {
"author" : "JavaUser21221",
"message" : "hai"
}
}
r.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot snapshot, String previousChildKey) {
Map<String,Object> newPost=(Map<String,Object>)snapshot.getValue();
String name1 = String.valueOf(newPost.get("Author"));
String message1 = String.valueOf(newPost.get("Title"));
System.out.println("Message: " + newPost.get("Author"));
System.out.println("Name: " + newPost.get("Title"));
}
});
suppose you have followig structure in your firebase database :
users:{ uid:[userid]
name:[username]
}
Student:{ rollno:[rollno]
name:[studendname]
}
Then to access the users child you can use the url ref.child('users/'+userid).addValueEventListener(....
This is the final answer i founds out
ref1.addChildEventListener(new ChildEventListener() {
// Retrieve new posts as they are added to Firebase
#Override
public void onChildAdded(DataSnapshot snapshot, String previousChildKey) {
Map<String,Object> newPost=(Map<String,Object>)snapshot.getValue();
String name1 = String.valueOf(newPost.get("Name"));
String message1 = String.valueOf(newPost.get("Message"));
System.out.println("---------------- full data ---------------------");
System.out.println("Message: " + newPost.get("Message"));
System.out.println("Name: " + newPost.get("Name"));
System.out.println("----------------- end of full data --------------------");
if(name1.equals("CCCCC"))
{
System.out.println("---------------- conditioned data ---------------------");
System.out.println("Message: " + newPost.get("Message"));
System.out.println("Name: " + newPost.get("Name"));
System.out.println("----------------- end of conditioned data --------------------");
}
}
#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(FirebaseError firebaseError) {
}
});
}
});

Categories

Resources