Ways to utilize the image string obtained from the .getExtra method

I have successfully created a listview in my app and parsed JSON data into it, including images and text. Now I am facing an issue where I need to pass the image to another activity when the user clicks on it. I can easily pass text data using putExtra, but I'm struggling with passing and displaying the image in the new activity using getExtra. Here's a glimpse of my code: In the first activity:

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            Intent intent = new Intent(MainActivity.this, Testic.class);
            String email = list.get(position).getEmail();
            String phone = list.get(position).getPhone();
            String name = list.get(position).getName();
            String imageUrl = list.get(position).getImage();
            
            intent.putExtra("email", email);
            intent.putExtra("phone", phone);
            intent.putExtra("name", name);
            intent.putExtra("imageUrl", imageUrl);
            startActivity(intent);
        }
    });

In the second activity:

        TextView emailText = (TextView) findViewById(R.id.emailText);
    emailText.setText(getIntent().getExtras().getString("email"));

    TextView phoneText = (TextView) findViewById(R.id.phoneText);
    phoneText.setText(getIntent().getExtras().getString("phone"));

    TextView nameText = (TextView) findViewById(R.id.nameText);
    nameText.setText(getIntent().getExtras().getString("name"));

    ImageView imageView = (ImageView) findViewById(R.id.imageView);
    // Missing implementation for image parsing

While everything else seems to be working smoothly, the challenge remains in correctly binding and displaying the image in the ImageView.

Answer №1

To implement this feature, follow these steps:

    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView imageView;

    public DownloadImageTask(ImageView imageView) {
        this.imageView = imageView;
    }

    protected Bitmap doInBackground(String... urls) {
        String imageUrl = urls[0];
        Bitmap imageBitmap = null;
        try {
            InputStream inStream = new java.net.URL(imageUrl).openStream();
            imageBitmap = BitmapFactory.decodeStream(inStream);
        } catch (Exception exception) {
            Log.e("Error", exception.getMessage());
            exception.printStackTrace();
        }
        return imageBitmap;
    }

    protected void onPostExecute(Bitmap result) {
        imageView.setImageBitmap(result);
    }
}

To use the method, add this code inside onCreate:

 new DownloadImageTask((ImageView) findViewById(R.id.imageview))
            .execute(getIntent().getExtras().getString("image_url"));

By following these instructions, you should be able to successfully fetch and display the image.

Answer №3

Make sure to include the image path in putExtra when sending it through intent. Avoid sending images as Bitmap or ImageView as they can be memory intensive.

Here's an example of how to do it:

intent.putExtra("imagePath", filepath); 

Then, retrieve the image path from the intent and use it like this:

String image_path = getIntent().getStringExtra("imagePath");
Bitmap bitmap = BitmapFactory.decodeFile(image_path);
myImageView.setImageDrawable(bitmap);

Answer №4

The outcome varies based on the String that was sent. Below is a possible solution:

Uri uri = Uri.parse(getIntent().getExtras().getString("image"));
ImageView image = (ImageView) findViewById(R.id.image);
image.setImageURI(uri);

"image" should be an identifier in your layout xml.

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

Utilizing multiple UILocalNotifications simultaneously

Hey there, I've encountered an issue with using UILocalNotification. I'm receiving notifications from a server and storing the data in a MutableArray. Here's a snippet of what it looks like: idnoty * id of notification titlenoty * title of ...

Retrieving a JavaScript variable's value in Selenium with Python

rwdata = driver.find_elements_by_xpath( "/html/body/div[2]/div/div/div/form[2]/div[2]/table/tbody") This table contains the value of variable r as text/javascript type. for r in rwdata: print(r.text) if r.text != "Booked": ...

Tips for converting a JSON map object into an array of objects using the Jackson library

Here is the JSON structure I am working with: { "blabla": { "1": { "foo": "foo1", "bar": "bar1" }, "22": { "foo": "foo22", "bar": "bar22" } } } This JSON represents a ...

What is the best way to distinguish between the app ID and version in Ionic framework?

I successfully launched an application on Android using the ionic framework. Now, I am preparing to launch the app on iOS as well. In order to do this, I need to obtain the specific id and version for both iOS and Android separately. The snippet from my ...

Converting a JSON dataset into various languages of the world

I am in possession of a large JSON dataset containing English conversations and I am curious about potential tools or methods that could facilitate translating them into Arabic. Are there any suggestions? ...

What is the best way to modify my if statement to avoid output duplication in my outfile?

When testing for a key, I either do a json.dump if it's present or add it if it's not. Additionally, I check for two other keys and add them if they are absent. I have nested these secondary tests. The issue with the current code is that if the ...

Using PHP to send a JSON request via cURL

I am attempting to make a cURL request in PHP. The request I am trying to send is as follows: $ curl -H 'Content-Type: application/json' -d '{"username":"a", "password":"b","msisdn":"447000000001","webhook":"http://example.com/"}' http ...

How can PHP effectively interpret JSON strings when sent to it?

When working with JavaScript, I am using JSON.stringify which generates the following string: {"grid":[{"section":[{"id":"wid-id-1-1"},{"id":"wid-id-1-4"}]},{"section":[{"id":"wid-id-1-5"}]},{"section":[{"id":"wid-id-1-2"},{"id":"wid-id-1-3"}]}]} I am ma ...

Using VueJS to perform a filtering operation on the JSON data when a button is clicked

I need to implement a filter function for my fetched json data using buttons. When a button is clicked, only the data (in this case book names) that match the clicked button should be displayed while hiding the others until another button is clicked. The ...

Attempting to comprehend the error message "TypeError: list indices must be integers or slices, not str"

### The following line executes without errors health_data_json = resp.json()["data"]["metrics"] ### However, this line results in a "TypeError: list indices must be integers or slices, not str" message energy_data_json = resp.json()[ ...

Unusual occurrences of backslashes in arrays when using JSON.stringify

While experimenting with JavaScript, I observed an unusual behavior when inserting a backslash \ into a string within an array and using JSON.stringify() to print it. Normally, the backslash is used for escaping special characters, but what if we actu ...

Is there a way to convert a flat JSON into several instances of a sub-class through deserialization?

Here is a flat JSON string that needs to be deserialized in Java using Jackson: {"ccy":"EUR", "value1":500, "value2":200, "date":"2017-07-25", "type":"", ... <many other pairs>} To deserialize this JSON string, we can create the following ...

Using JSON Serialization in MVC3

How do I handle JSON serialization for the object being returned as null in my controller? public class CertRollupViewModel { public IEnumerable<CertRollup> CertRollups { get; set; } } public class CertRollup { public decimal TotalCpm { get ...

Exploring JSON Object Arrays within the JFrog Mission Control API

I have recently upgraded to Mission Control version 1.1 While trying to interact with the REST API for repository creation, I encountered an issue with my JSON input: { "scriptMappings": [{ "scriptNames": ["virtual-repo"], "scriptUserInputs": [{ ...

A guide on simultaneously updating multiple series in Highcharts

I am currently utilizing Highcharts to display multiple series on a single chart. These series are fetched from a file that contains the data in JSON format. The file is regularly updated with new data, and I have implemented a function to re-read the file ...

Utilizing two imports within the map() method

I have been considering the idea of incorporating two imports within map() in my React code. This is how my code looks: {this.state.dataExample.map(item => ( <ItemsSection nameSection={item.name} /> item.dat ...

Link Android with Python

I am working on an Android application that captures images and also have Python code for extracting image features. I am looking to connect these two components so that the Python code can receive images from the Android application. I have heard about bu ...

Let's explore further - delving into JSON & array manipulation using the foreach loop in Pure JavaScript

Although I have some experience with Java Script, I still consider myself a beginner in certain areas, particularly when it comes to accessing JSON objects and arrays. I've tried various syntax and options for accessing arrays using [], but so far, I ...

Error: Lambda function response malformed, please check API Gateway configuration

According to the official documentation, my JSON response should include a body, headers, and a status code, which it does. However, when testing in API Gateway, I am encountering issues with receiving a malformed response. Below is the output of my metho ...

What is the Best Way to Understand CloudKit Error Messages?

I'm currently working on a php script that aims to create a record in a CloudKit database. However, I keep encountering this error: object(stdClass)#1 (3) { ["uuid"]=> string(36) "c70072a1-fab6-491b-a68f-03b9056223e1" ["serverErrorCode"]=> ...