Encountering a ClassCastException error when working on a Firebase function in Android Java that involves dealing with

I am facing an issue while trying to create a Task method in an Android app that calls a Cloud function (specifically Firebase) and encounters a ClassCastException error "String cannot be cast to Uri" within the onCompleteListener. What steps should I take to resolve this problem?

Below is the relevant code snippet:

private Task<Uri> getProfilePicture(){
    return functions
            .getHttpsCallable("getProfilePicture")
            .call()
            .continueWith(task -> (Uri) task.getResult().getData())
            .addOnCompleteListener(task -> {
                String pfp = task.getResult().toString();
                Uri pfp2 = Uri.parse(pfp);
                setProfilePhoto(pfp2);
            });
}

The code for the Cloud function is as follows:

import * as functions from 'firebase-functions';
import admin = require('firebase-admin');
admin.initializeApp()

export const getProfilePicture = functions.https.onRequest((request, response) => {

const promise = admin.storage().bucket().file('usersPfp/aomkefQvkRQCuB66m6L9m94k9Bf1').getSignedUrl({
    action: 'read',
    expires: '03-09.2441'
})

const p2 = promise.then(GetSignedUrlResponse => {
    const data = GetSignedUrlResponse[0]
    return response.send({"data": data})
})

p2.catch(error =>{
    console.log(error)
    return response.status(500).send({"error": error})
})
})

Additionally, here is the exception that is being thrown:

2020-01-19 15:41:04.150 28029-28029/com.happs.medrate E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.happs.medrate, PID: 28029
com.google.android.gms.tasks.RuntimeExecutionException: java.lang.ClassCastException: java.lang.String cannot be cast to android.net.Uri
    at com.google.android.gms.tasks.zzu.getResult(Unknown Source:15)
    at com.happs.medrate.viewmodel.main.AccountFragmentViewModel.lambda$getProfilePicture$1$AccountFragmentViewModel(AccountFragmentViewModel.java:76)
    at com.happs.medrate.viewmodel.main.-$$Lambda$AccountFragmentViewModel$OKnCSppMNZTxWBSaV67HE9UL6mo.onComplete(Unknown Source:2)
    at com.google.android.gms.tasks.zzj.run(Unknown Source:4)
    at android.os.Handler.handleCallback(Handler.java:789)
    at android.os.Handler.dispatchMessage(Handler.java:98)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6944)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
 Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to android.net.Uri
    at com.happs.medrate.viewmodel.main.AccountFragmentViewModel.lambda$getProfilePicture$0(AccountFragmentViewModel.java:74)
    at com.happs.medrate.viewmodel.main.-$$Lambda$AccountFragmentViewModel$gUAaj3fCSegHGtCnpDov7VKk9aQ.then(Unknown Source:0)
    at com.google.android.gms.tasks.zzd.run(Unknown Source:5)
    at android.os.Handler.handleCallback(Handler.java:789) 
    at android.os.Handler.dispatchMessage(Handler.java:98)  
    at android.os.Looper.loop(Looper.java:164) 
    at android.app.ActivityThread.main(ActivityThread.java:6944)  
    at java.lang.reflect.Method.invoke(Native Method)   
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)    
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)    

Answer №1

For a smoother process, consider using

continueWith(task -> Uri.parse(task.getResult().getData()))
.

Once implemented, there is no longer a necessity to parse it within the addOnCompleteListener.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The display of the key property is missing on the rendered page in a React TypeScript project

While working with Typescript React, I encountered an error message: react-jsx-dev-runtime.development.js:87 Warning: Each child in a list should have a unique "key" prop. Even though I included a key in the li tag like this: const MyMenuItem: ...

Exploring the Checkbox Array Functionality on Android

I'm working on creating a listview with checkboxes and utilizing the listview's built-in checkbox method. After referring to a helpful stackoverflow post, I have managed to get it up and running smoothly except for one issue. When there are four ...

Ways to access the current element in the Evernote editor that corresponds to the cursor's position?

It seems that Evernote editor uses a Rich Text Editor which differs from the input or textarea tag. Therefore, I am unable to use the provided code to determine its type. Is there a way to retrieve the current element of the Evernote editor where the curso ...

What could be causing Loudev jQuery multiselect to generate duplicates?

The concept involves allowing users to select a main bank branch via a search textbox that triggers a jQuery AJAX request. If the user wishes to add more branches, they can use a multiselect functionality provided later in the form for selecting one or mul ...

Switch back and forth between `display: none` and `display: flex` using JavaScript

There is a JavaScript function in place for a responsive navigation system that includes a burger button to toggle the visibility of the navigation menu when the screen size is too small. The issue I am facing is that despite setting the CSS style as disp ...

Having trouble importing Bootstrap into Next.js? It seems like the issue may be related to the

I am currently facing an issue with importing bootstrap 5.3.2 (not react-bootstrap) into my NextJS 14.1.0 project that utilizes the new App Router. My goal is to strategically utilize individual Bootstrap components (not through data-attrs). I managed to ...

Tips for integrating a calendar into a website

After researching, I came across this code for adding a calendar to my webpage: <!DOCTYPE html> <html> <head> <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/ ...

Sending data to Layout for customizable routes (App Router) in Next.js version 13

Looking to pass props to the Layout component for dynamic routes in my project structure: /app -/(site) --/layout.tsx --/page.tsx --/[slug]/page.tsx --/[slug]/layout.tsx In the site layout: export default async function IndexRoute({ children }: { chil ...

Encountering a parser error while attempting to parse a date

Currently attempting to parse dates in the format of 23-May-2016 and 24-May 2016. Here is a snippet of the code used for date parsing: SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy"); Date validityDate = null; Date ...

MySQL error unknown column in having clause in Hibernate despite column existing

I am facing an issue with a JPQL query in a repository, which is equivalent to the MySQL query provided below: SELECT DISTINCT ji.* FROM tracker_job_item AS ji JOIN tracker_work AS w ON ji.id=w.tracker_job_item_id JOIN tracker_work_quantity AS wq on w.id= ...

Remove any unnecessary characters from the beginning of the string and keep track of the total number of spaces removed

How can I determine the number of characters that have been removed from the beginning of a string? This string is retrieved from a textarea input, and knowing this information will help me calculate the new position of the cursor selection. While $.trim( ...

Turn off Keyguard when SMS is received

I am currently working on an SMS android application and one of the features I am looking to incorporate is the ability for the screen lock to automatically disable upon receiving an SMS, eliminating the need for the user to unlock their phone to read the ...

Troubleshooting: jQuery and jQuery UI slider event not triggering on jump/click action

I am working on a jQuery slider that is designed to cycle through a series of divs. I have noticed that when I drag the slider and release it, the handleSlider() function is triggered. However, if I simply click on a random point within the slider, the f ...

Modifying a document by ID in Mongoose without altering a specific field

In my code, I have successfully established a new connection using Mongoose and implemented a schema. Retrieving attributes from the collection is also working as intended. However, when attempting to update my collection, I am encountering difficulties. T ...

Is it possible to extract column names without explicitly specifying them?

With my automation script in Java/Selenium/Excel, I am currently verifying information in the database using a specific process: //Get values from Excel. Excel user will specify what table and what user String table=currentTestSuiteXLS.getCellData(current ...

Bypass the table if not detected with selenium

In my HTML code, I have tables that contain information about different movies. Each table includes details such as genre, time, days, location, date range, seating, and actors. However, some movies may not have a complete table, so I want to replace miss ...

Incorrect invocation of a default package visibility Android method within the ART runtime

I have two classes in different packages structured like this: Base class: package com.example.artpackageprivate.base; public class Base { protected final Context mContext; public Base(final Context context) { mContext = context; } ...

Tips for creating a fixed AppBar and table headers that are stacked underneath each other on a single page while scrolling, using Material UI

Check out these screenshots of the AppBar and Table: View screenshot at the top of the page. Screenshot when scrolling down Take a look at the code for the AppBar and Table: <AppBar position="static" style = {{background : "#00009A"}}> ...

What steps can I take to ensure that the browser prints out a PDF copy of a webpage?

Imagine you have a website page saved as example.html, and also a printable file named example.pdf. Is there a way to prompt the browser to open and print example.pdf instead of example.html when users attempt to print? If this isn't achievable, how ...

What is preventing this JSON object from being parsed correctly?

Within my JavaScript file, The process of declaring and parsing the ajax response text is as follows: var subcats = JSON.parse(this.responseText); The actual responseText that needs to be parsed looks like this: {"presubcatId":"1","precatId":"1","presu ...