Is there any way to remove the link and only get the file name of the file in the code? Im trying to access to load a model in my app that is created in android studio
This one doesn't work because it provides a link instead the name of the file
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference modelRef = storage.getReference().child(myPlants.getPlantModel());
This code works
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference modelRef = storage.getReference().child(pre4.glb);
Is there a way to get the file name only and not the token? Please help.
The assigned text in the getPlantModel is the link.
Database Screenshot
public class PlantAR extends AppCompatActivity {
private ProgressDialog progressDialog;
Button downloadButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_plant_ar);
Intent intent = getIntent();
MyPlants myPlants = (MyPlants) intent.getSerializableExtra("plants");
FirebaseApp.initializeApp(this);
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference modelRef = storage.getReference().child("pre6.glb");
ArFragment arFragment = (ArFragment) getSupportFragmentManager()
.findFragmentById(R.id.fragmentAR);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Model downloading Please Wait...........");
downloadButton = findViewById(R.id.downloadModel);
findViewById(R.id.downloadModel)
.setOnClickListener(v -> {
try {
File file = File.createTempFile("pre6", "glb");
progressDialog.show();
modelRef.getFile(file).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
buildModel(file);
}
});
} catch (IOException e) {
e.printStackTrace();
}
});
arFragment.setOnTapArPlaneListener((hitResult, plane, motionEvent) -> {
AnchorNode anchorNode = new AnchorNode(hitResult.createAnchor());
anchorNode.setRenderable(renderable);
arFragment.getArSceneView().getScene().addChild(anchorNode);
});
}
private ModelRenderable renderable;
private void buildModel(File file) {
RenderableSource renderableSource = RenderableSource
.builder()
.setSource(this, Uri.parse(file.getPath()), RenderableSource.SourceType.GLB)
.setRecenterMode(RenderableSource.RecenterMode.ROOT)
.build();
ModelRenderable
.builder()
.setSource(this, renderableSource)
.setRegistryId(file.getPath())
.build()
.thenAccept(modelRenderable -> {
downloadButton.setVisibility(View.GONE);
progressDialog.dismiss();
Toast.makeText(this, "Model built", Toast.LENGTH_SHORT).show();;
renderable = modelRenderable;
});
}
Related
I am currently building a project which allows the user to take a photo of something and use that photo. I was wondering if there were any other methods out there that does not require me to download any Plugins or NuGet Packages?
You need to create a ICameraPickerService in Xamarin Forms :
public interface IPhotoPickerService
{
Task<byte[]> GetImageStreamAsync();
}
In iOS , create the CameraPickerService :
[assembly: Dependency(typeof(CameraPickerService))]
namespace DependencyServiceDemos.iOS
{
public class CameraPickerService: ICameraPickerService
{
TaskCompletionSource<byte[]> taskCompletionSource;
UIImagePickerController imagePicker;
public Task<byte[]> GetImageStreamAsync()
{
// Create and define UIImagePickerController
imagePicker = new UIImagePickerController
{
SourceType = UIImagePickerControllerSourceType.Camera,
MediaTypes = UIImagePickerController.AvailableMediaTypes(UIImagePickerControllerSourceType.Camera)
};
// Set event handlers
imagePicker.FinishedPickingMedia += OnImagePickerFinishedPickingMedia;
imagePicker.Canceled += OnImagePickerCancelled;
// Present UIImagePickerController;
UIWindow window = UIApplication.SharedApplication.KeyWindow;
var viewController = window.RootViewController;
viewController.PresentModalViewController(imagePicker, true);
// Return Task object
taskCompletionSource = new TaskCompletionSource<byte[]>();
return taskCompletionSource.Task;
}
void OnImagePickerFinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs args)
{
UIImage image = args.EditedImage ?? args.OriginalImage;
if (image != null)
{
// Convert UIImage to .NET Stream object
NSData data;
if (args.ReferenceUrl.PathExtension.Equals("PNG") || args.ReferenceUrl.PathExtension.Equals("png"))
{
data = image.AsPNG();
}
else
{
data = image.AsJPEG(1);
}
Stream stream = data.AsStream();
UnregisterEventHandlers();
// Set the Stream as the completion of the Task
taskCompletionSource.SetResult(data.ToArray());
}
else
{
UnregisterEventHandlers();
taskCompletionSource.SetResult(null);
}
imagePicker.DismissModalViewController(true);
}
void OnImagePickerCancelled(object sender, EventArgs args)
{
UnregisterEventHandlers();
taskCompletionSource.SetResult(null);
imagePicker.DismissModalViewController(true);
}
void UnregisterEventHandlers()
{
imagePicker.FinishedPickingMedia -= OnImagePickerFinishedPickingMedia;
imagePicker.Canceled -= OnImagePickerCancelled;
}
}
}
Not forgetting to add permission in Info.plist :
<key>NSCameraUsageDescription</key>
<string>Use Camera</string>
In addition , iOS need to run in a physical device.
In Android , create the CameraPickerService :
[assembly: Dependency(typeof(CameraPickerService))]
namespace DependencyServiceDemos.Droid
{
public class CameraPickerService : ICameraPickerService
{
public Task<byte[]> GetImageStreamAsync()
{
// Define the Intent for getting images
Intent getImageByCamera = new Intent("android.media.action.IMAGE_CAPTURE");
// Start the camera (resumes in MainActivity.cs)
MainActivity.Instance.StartActivityForResult(
getImageByCamera,
MainActivity.PickImageId);
// Save the TaskCompletionSource object as a MainActivity property
MainActivity.Instance.PickImageTaskCompletionSource = new TaskCompletionSource<byte[]>();
// Return Task object
return MainActivity.Instance.PickImageTaskCompletionSource.Task;
}
}
}
Adding permission in AndroidMainfest.xml :
<uses-permission android:name= "android.permission.CAMERA" />
<uses-permission android:name= "android.permission.WRITE_EXTERNAL_STORAGE" />
Get Image data in MainActivity :
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
internal static MainActivity Instance { get; private set; }
public int CAMERA_JAVA_REQUEST_CODE = 1;
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Instance = this;
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
DependencyService.Register<ITextToSpeechService, TextToSpeechService>();
}
// Field, property, and method for Picture Picker
public static readonly int PickImageId = 1000;
public TaskCompletionSource<byte[]> PickImageTaskCompletionSource { set; get; }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent intent)
{
base.OnActivityResult(requestCode, resultCode, intent);
if (requestCode == PickImageId)
{
if ((resultCode == Result.Ok) && (intent != null))
{
Bundle bundle = intent.Extras;
Bitmap bitmap = (Bitmap)bundle.Get("data");
//// Set the Stream as the completion of the Task
MemoryStream memoryStream = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 50, memoryStream);
PickImageTaskCompletionSource.SetResult(memoryStream.ToArray());
}
else
{
PickImageTaskCompletionSource.SetResult(null);
}
}
}
}
Finally , show image in ContentPage of Forms :
async void OnPickPhotoButtonClicked(object sender, EventArgs e)
{
(sender as Button).IsEnabled = false;
byte[] data = await DependencyService.Get<IPhotoPickerService>().GetImageStreamAsync();
MemoryStream stream = new MemoryStream(data);
if (stream != null)
{
image.Source = ImageSource.FromStream(() => stream) ;
}
(sender as Button).IsEnabled = true;
}
The effect :
Note : If want to pick a Photo from the Picture Library, you can have a look at this official document .
I want my firebase database link to be updated depending on what the user keys in inside the searchview but the link is not updated unless I open another activity and jump back to it.I have attacked my code in the bottom. So how do I refresh it automatically ?
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener()
{
#Override
public boolean onQueryTextSubmit(String query) {
query = sv.getQuery().toString();
Toast.makeText(MainMenu.this,query, Toast.LENGTH_SHORT).show();
makeItem();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
public void makeItem ()
{
lv = findViewById(R.id.listView);
db = FirebaseDatabase.getInstance().getReferenceFromUrl("https://vsem-inventory.firebaseio.com/ItemList").orderByChild("ProductName").startAt(query).endAt(query+"\uf8ff");
FirebaseListOptions<ItemObject> options = new FirebaseListOptions.Builder<ItemObject>()
.setLayout(R.layout.content_main_menu_list)
.setQuery(db,ItemObject.class)
.build();
mAdapter = new FirebaseListAdapter<ItemObject>(options) {
#Override
protected void populateView(#NonNull View v, #NonNull ItemObject model, int position) {
final TextView tvAmount = v.findViewById(R.id.amount);
final TextView tvName = v.findViewById(R.id.name);
final TextView tvSerial = v.findViewById(R.id.serialNo);
final TextView tvSupplier = v.findViewById(R.id.supplierName);
final ImageView more = v.findViewById(R.id.more);
ImageView statusimg = v.findViewById(R.id.status);
Drawable paidIcon = v.getResources().getDrawable(R.drawable.succes);
Drawable lateIcon = v.getResources().getDrawable(R.drawable.late);
tvName.setText(model.getProductName());
tvSerial.setText(model.getSerialNo());
tvAmount.setText(model.getQuantity());
tvSupplier.setText(model.getModel());
final String Remarks = model.getRemarks();
final String cat = model.getCategory();
if(model.getQuantity().equals("0"))
statusimg.setImageDrawable(lateIcon);
else
statusimg.setImageDrawable(paidIcon);
more.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
String serialNo = tvSerial.getText().toString();
String itemName = tvName.getText().toString();
String quan = tvAmount.getText().toString();
String supplier = tvSupplier.getText().toString();
showMenu(itemName,more,serialNo,quan,supplier,cat,Remarks);
}
});
}
};
lv.setAdapter(mAdapter);
}
The standard way is to call notifyDataSetChanged() after setting your adapter to your list view
Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.
mAdapter.notifyDataSetChanged();
Although I have seen some situations where only using this does not work and must be followed by these 2 commands.
lv.invalidateViews();
lv.scrollBy(0, 0);
And if all else comes to fail falling back on destroying and redrawing the list view might be your only viable option.
lv.destroyDrawingCache();
lv.setVisibility(ListView.INVISIBLE);
lv.setVisibility(ListView.VISIBLE);
EDIT : After looking at it a while more I just noticed you're missing listeners for your firebase. I assume you already have them somewhere as you already have the list but failing your refresh functions, what you can try is restarting the listeners whenever you're done with a query.
lv.setAdapter(mAdapter);
mAdapter.stopListening();
mAdapter.startListening();
I want to show dialogue when new version is available.
I want to make a json file into my web server, and I will manually update my app version in json file. and my app will parse this json file and will notify users and showing dialogue box to update my app from playstore link by clicking Update button.
I don't want to make this with firebase.
public class ForceUpdateAsync extends AsyncTask<String, String, JSONObject>{
private String latestVersion;
private String currentVersion;
private Context context;
public ForceUpdateAsync(String currentVersion, Context context){
this.currentVersion = currentVersion;
this.context = context;
}
#Override
protected JSONObject doInBackground(String... params) {
try
{
latestVersion = Jsoup.connect("https://play.google.com/store/apps/details?id="+context.getPackageName()+"&hl=en")
.timeout(30000)
.userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
.referrer("http://www.google.com")
.get()
.select("div[itemprop=softwareVersion]")
.first()
.ownText();
} catch (IOException e) {
e.printStackTrace();
}
return new JSONObject();
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
if(latestVersion!=null){
if(!currentVersion.equalsIgnoreCase(latestVersion)){
// Toast.makeText(context,"update is available.",Toast.LENGTH_LONG).show();
if(!(context instanceof SplashActivity)) {
if(!((Activity)context).isFinishing()){
showForceUpdateDialog();
}
}
}
}
super.onPostExecute(jsonObject);
}
public void showForceUpdateDialog(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(new ContextThemeWrapper(context,
R.style.DialogDark));
alertDialogBuilder.setTitle(context.getString(R.string.youAreNotUpdatedTitle));
alertDialogBuilder.setMessage(context.getString(R.string.youAreNotUpdatedMessage) + " " + latestVersion + context.getString(R.string.youAreNotUpdatedMessage1));
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton(R.string.update, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + context.getPackageName())));
dialog.cancel();
}
});
alertDialogBuilder.show();
}
}
after that in your splash activity just use this code
public void forceUpdate()
{
PackageManager packageManager = this.getPackageManager();
PackageInfo packageInfo = null;
try {
packageInfo = packageManager.getPackageInfo(getPackageName(),0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
String currentVersion = packageInfo.versionName;
new ForceUpdateAsync(currentVersion,BaseActivity.this).execute();
}
I am trying to load image in my Firebase storage from my database reference. I am then using Picasso (implementation 'com.squareup.picasso:picasso:2.71828') to retrieve the image from the database reference. The entirety of the code I am using can be found here https://github.com/kshitiz1007/Lets-Chat though with updated libraries and slightly update ui. But the two files of note are SettingActivity, where user chooses profile image and text status to put into database and ProfileActivity, where the the profile image is called for use by Picasso.
My understanding is that in SettingActivity, the profile image as well as the thumb size version of the profile image, are being saved to a hashmap in SettingActivity:
update_HashMap.put("image",downloadUrl);
update_HashMap.put("thumb_image",thumb_download_url);
//--------ADDING URL INTO DATABASE REFERENCE-------
mDatabaseReference.updateChildren(update_HashMap).addOnCompleteListener(new
My problem is that calling when Picasso calls load, display image of source (String display_image = dataSnapshot.child("image").getValue().toString();) never loads.
But I do not know the mechanism nor how the image is retrieved from Storage using the Firebase database reference. When Picasso tries to get the image from the database reference it says in Run
Log
D/Picasso: Main created [R22]
Request{com.google.android.gms.tasks.zzu#5843814}
...
D/Picasso: Main errored [R22]+246ms Unrecognized type of request:
Request{com.google.android.gms.tasks.zzu#5843814}
Firebase Database
Firebase Storage
If you view the second picture, the image seems to have a pointer to a task and Picasso doesn't know how to use that information.
Below is from SettingActivity.java
public class SettingActivity extends AppCompatActivity {
...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//-----STARTING GALLERY----
if(requestCode == GALLERY_PICK && resultCode == RESULT_OK){
Uri sourceUri = data.getData();
//-------CROPPING IMAGE AND SETTING MINIMUM SIZE TO 500 , 500------
CropImage.activity(sourceUri).
setAspectRatio(1,1).
setMinCropWindowSize(500,500).
start(SettingActivity.this);
}
//------START CROP IMAGE ACTIVITY------
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE ) {
//------CROP IMAGE RESULT------
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
mProgressDialog.setTitle("Uploading Image");
mProgressDialog.setMessage("Please wait while we process and upload the image...");
mProgressDialog.setCancelable(false);
mProgressDialog.setProgress(ProgressDialog.STYLE_SPINNER);
mProgressDialog.show();
Uri resultUri = result.getUri();
File thumb_filepath = new File(resultUri.getPath());
try {
//--------COMPRESSING IMAGE--------
Bitmap thumb_bitmap = new Compressor(this).
setMaxWidth(200).
setMaxHeight(200).
setQuality(75).
compressToBitmap(thumb_filepath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumb_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
thumb_bytes= baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
final StorageReference filepath = mStorageReference.child("profile_image").child(uid+".jpg");
final StorageReference thumb_file_path = mStorageReference.child("profile_image").child("thumbs").child(uid+".jpg");
//------STORING IMAGE IN FIREBASE STORAGE--------
filepath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
#SuppressWarnings("VisibleForTests")
final String downloadUrl= filepath.getDownloadUrl().toString();
final UploadTask uploadTask = thumb_file_path.putBytes(thumb_bytes);
//---------- STORING THUMB IMAGE INTO STORAGE REFERENCE --------
uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> thumb_task) {
#SuppressWarnings("VisibleForTests")
String thumb_download_url = uploadTask.getSnapshot().getMetadata().getReference().getDownloadUrl().toString();
// String thumb_download_url = thumb_task.getResult().getDownloadUrl().toString();
if(thumb_task.isSuccessful()){
Map update_HashMap=new HashMap();
// Download Url stored to HashMap but where is this HashMap and how does it reference storage from database
update_HashMap.put("image",downloadUrl);
update_HashMap.put("thumb_image",thumb_download_url);
//--------ADDING URL INTO DATABASE REFERENCE--------
mDatabaseReference.updateChildren(update_HashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
mProgressDialog.dismiss();
Toast.makeText(SettingActivity.this, "Uploaded Successfuly...", Toast.LENGTH_SHORT).show();
}
else{
mProgressDialog.dismiss();
Toast.makeText(getApplicationContext(), " Image is not uploading...", Toast.LENGTH_SHORT).show();
}
}
});
}
else{
mProgressDialog.dismiss();
Toast.makeText(getApplicationContext(), " Error in uploading Thumbnail..", Toast.LENGTH_SHORT).show();
}
}
});
}
else{
mProgressDialog.dismiss();
Toast.makeText(getApplicationContext(), " Image is not uploading...", Toast.LENGTH_SHORT).show();
}
}
});
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
}
Below is from ProfileActivity.java
mfriendReqReference = FirebaseDatabase.getInstance().getReference().child("friend_request");
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("users").child(user_id);
mFriendDatabase = FirebaseDatabase.getInstance().getReference().child("friends");
mNotificationReference = FirebaseDatabase.getInstance().getReference().child("notifications");
mRootReference = FirebaseDatabase.getInstance().getReference();
mFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
//----fOR SETTING ONLINE---
getmDatabaseReference = FirebaseDatabase.getInstance().getReference().child("users").child(mFirebaseUser.getUid());
mProgressDialog = new ProgressDialog(ProfileActivity.this);
mProgressDialog.setTitle("Fetching Details");
mProgressDialog.setMessage("Please wait...");
mProgressDialog.setProgress(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
mCurrent_state = "not_friends"; // 4 types--- "not_friends" , "req_sent" , "req_received" & "friends"
//----ADDING NAME , STATUS AND IMAGE OF USER----
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String display_name = dataSnapshot.child("name").getValue().toString();
String display_status = dataSnapshot.child("status").getValue().toString();
String display_image = dataSnapshot.child("image").getValue().toString();
mProfileName.setText(display_name);
mProfileStatus.setText(display_status);
Picasso.get()
.load(display_image)
.placeholder(R.drawable.user_img)
.memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
.into(mProfileImage);
// ---------------------------------------------------------------------------------
//https://stackoverflow.com/questions/46071230/use-glide-load-into-imageview-but-delay?rq=1
/*RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.user_img);
Glide.with(ProfileActivity.this)
.setDefaultRequestOptions(requestOptions)
.load(Uri.parse(display_image))
// .placeholder(R.drawable.user_img)
.into(mProfileImage);*/
//----ADDING TOTAL NO OF FRIENDS---
mFriendDatabase.child(user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
long len = dataSnapshot.getChildrenCount();
mprofileFriendCount.setText("TOTAL FRIENDS : "+len);
//----SEEING THE FRIEND STATE OF THE USER---
//----ADDING THE TWO BUTTON-----
mfriendReqReference.child(mFirebaseUser.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//----CHECKING IF FRIEND REQUEST IS SEND OR RECEIVED----
if(dataSnapshot.hasChild(user_id)){
String request_type = dataSnapshot.child(user_id).child("request_type").getValue().toString();
if(request_type.equals("sent")){
mCurrent_state="req_sent";
mProfileSendReqButton.setText("Cancel Friend Request");
mProfileDeclineReqButton.setVisibility(View.INVISIBLE);
mProfileDeclineReqButton.setEnabled(false);
}
else if(request_type.equals("received")){
mCurrent_state="req_received";
mProfileSendReqButton.setText("Accept Friend Request");
mProfileDeclineReqButton.setVisibility(View.VISIBLE);
mProfileDeclineReqButton.setEnabled(true);
}
mProgressDialog.dismiss();
}
//---USER IS FRIEND----
else{
mFriendDatabase.child(mFirebaseUser.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mProfileDeclineReqButton.setVisibility(View.INVISIBLE);
mProfileDeclineReqButton.setEnabled(false);
if(dataSnapshot.hasChild(user_id)){
mCurrent_state="friends";
mProfileSendReqButton.setText("Unfriend This Person");
}
mProgressDialog.dismiss();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
mProgressDialog.dismiss();
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(ProfileActivity.this, "Error fetching Friend request data", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Correct way of getting downloadUrl after uploading here
I am creating a chat application with Firebase and after creating it I am facing the issue that it is too slow. When a message is sent it will go to the server first and then it will show in the message list.
Can I save chat locally or can I show message on my thread before saving on db?
Here is my chat page:
namespace XamarinChatApp.View
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ChatPage : ContentPage
{
DBFire db = new DBFire();
Room rm = new Room();
public ChatPage()
{
InitializeComponent();
MessagingCenter.Subscribe<RoomPage, Room>(this, "RoomProp", (page, data) =>
{
rm = data;
_lstChat.BindingContext = db.subChat(data.Key);
MessagingCenter.Unsubscribe<RoomPage, Room>(this, "RoomProp");
});
}
async void Handle_Clicked(object sender, System.EventArgs e)
{
// firsth chat object
//room name 1---okey
var chatOBJ = new Chat { UserMessage = _etMessage.Text, UserName = User.UserName };
_etMessage.Text = "";
await db.saveMessage(chatOBJ, rm.Key);
}
async void Upload_Photo(object sender, System.EventArgs e)
{
// firsth chat object
//room name 1---okey
await CrossMedia.Current.Initialize();
var imgData = await CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions());
await db.saveImage(imgData.GetStream());
// _img1.Source = ImageSource.FromStream(imgData.GetStream);
}
}
}