简体   繁体   中英

App crashes when I try to display image on an imageview in another activity

I am making an app that basically lets a user enter a url along with a title in an edit text and then by pressing a download button, the image will display on another activity. There are some other functions as well that aren't relevant right now. The problem I am having is that when I put in the id for the imageview from where the downloaded image should be displayed and press download for an image the app crashes. This is my code so far:

Main Activity:

package com.example.faraz.assignment2;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void dl(View view) {
        Intent intent = new Intent(this,DownloadActivity.class);
        startActivity(intent);
    }

    public void viewA(View view) {
        Intent viewPic = new Intent(this,ViewActivity.class);
        startActivity(viewPic);
    }
}

Main XML:

<?xml version="1.0" encoding="utf-8"?>
<android.widget.LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="top|center_vertical|center_horizontal|center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/download"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Download"
        android:onClick="dl"/>

    <Button
        android:id="@+id/delete"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Delete" />

    <Button
        android:id="@+id/view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="View"
        android:onClick="viewA"/>

    <Button
        android:id="@+id/range"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Range" />
</android.widget.LinearLayout>

ViewActivity is where I am trying to display the image:

package com.example.faraz.assignment2;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class ViewActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view);
    }
}

ViewActivity XML:

<?xml version="1.0" encoding="utf-8"?>
<android.widget.LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="top|center_vertical|center_horizontal|center"
    android:orientation="vertical"
    tools:context=".DownloadActivity">


    <ImageView
        android:id="@+id/pic"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:srcCompat="@tools:sample/avatars[0]" />
</android.widget.LinearLayout>

DownloadActivity is where the image is being downloaded from:

package com.example.faraz.assignment2;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;


public class DownloadActivity extends AppCompatActivity {

    private Button btn;
    private EditText et;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download);

        btn = (Button)findViewById(R.id.buttonD);
        et = (EditText)findViewById(R.id.link);

        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                try {
                    URL url = new URL(et.getText().toString());
                    new MyDownloadTask().execute(url);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    private class MyDownloadTask extends AsyncTask<URL, Integer, Bitmap> {
        @Override
        protected Bitmap doInBackground(URL... params) {
            URL url = params[0];
            Bitmap bitmap = null;
            try {
                URLConnection connection = url.openConnection();
                connection.connect();
                InputStream is = connection.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                bitmap = BitmapFactory.decodeStream(bis);
                bis.close();
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }

            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null) {
                ImageView myImage = (ImageView) findViewById(R.id.test);//error is here when I change id for imageview to the one in ViewActivity
                myImage.setImageBitmap(bitmap);
            } else {
                Toast.makeText(getApplicationContext(), "Failed to Download 
Image", Toast.LENGTH_LONG).show();
            }
        }
    }
}

The code for downloadactivity was taken from here

DownloadActivity XML:

<?xml version="1.0" encoding="utf-8"?>
<android.widget.LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/linear_layout"
    android:gravity="top|center_vertical|center_horizontal|center"
    android:orientation="vertical"
    tools:context=".DownloadActivity">


    <EditText
        android:id="@+id/link"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="URL"
        android:inputType="textPersonName" />

    <EditText
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Title"
        android:inputType="textPersonName" />

    <Button
        android:id="@+id/buttonD"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Download" />

    <ImageView
        android:id="@+id/test"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:srcCompat="@tools:sample/avatars" />
</android.widget.LinearLayout>

I would appreciate the help.

Edit: This is my DownloadActivity now but it still wont show the picture on ViewActivity:

btn = (Button)findViewById(R.id.buttonD);
et = (EditText)findViewById(R.id.link);
pic = (ImageView) findViewById(R.id.pic);


    btn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                String url = et.getText().toString();
                Glide.with(DownloadActivity.this).load(url).into(pic);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

runOnUiThread

added in API level 1

public final void runOnUiThread (Runnable action) Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.

DownloadActivity.this.runOnUiThread(new Runnable() 
    {
        public void run() {
            Log.d("UI thread", "I am the UI thread");
                         if (bitmap != null) {
                                      //remove line from here ImageView myImage = (ImageView)findViewById(R.id.test);
              //error is here when I change id for imageview to the one in ViewActivity
                    myImage.setImageBitmap(bitmap);
                                             } else {
                                          Toast.makeText(getApplicationContext(), "Failed to Download 
    Image", Toast.LENGTH_LONG).show();
                                                    }
                         }
    });

Edit 2

ImageView myImage = (ImageView) findViewById(R.id.test);

please initialise in onCreate();

replace with

ImageView myImage;

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_download);

    btn = (Button)findViewById(R.id.buttonD);
    et = (EditText)findViewById(R.id.link);

    // myImage Initialization 
    myImage = (ImageView) findViewById(R.id.test);


    btn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                URL url = new URL(et.getText().toString());
                new MyDownloadTask().execute(url);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

error is here when I change id for imageview to the one in ViewActivity

Because you can only find views by runing findViewById for the layout that is defined for that current Activity's setContentView .

When you open a new Activity, you lose access to the views that it is displaying, so therefore, you cannot find/use them.


Within the ViewActivity, I would suggest just using Picasso or Glide libraries to load an image from a URL and loading into R.id.pic without going through a separate Activity... If you did want a separate class, you could look into "headless Fragments"

This can be done much easily with lesser lines of codes. First in your MainActivity get the URL of the image from the user and pass it to your DownloadActivity using bundle and intent . Like this:

EditText urledititext = findViewById(R.id.url);
String url = urledititext .getText().toString();
Intent intent = new Intent(this,DownloadActivity.class);
intent.putExtra("url", url);
startActivity(intent);

This is how you can send the string url to the DownloadActivity .

In your download activity, just get the bundle and using glide library, you can fetch the image from the url and load in your imageview . Like this :

String url= bundle.getString("url");
Glide.with(DownloadActivity.this).load(url).into(imageView);

Remember to add glide library in your app level build.gradle like this :

implementation 'com.github.bumptech.glide:glide:4.8.0'

Update 1:

In case you want to send data from one activity to another, use the above method. If you are getting the URL and showing the image in a same activity, follow below steps:

In your DownloadActivity:

    btn = (Button)findViewById(R.id.buttonD);
    et = (EditText)findViewById(R.id.link);

    btn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                String url = et.getText().toString();
                Glide.with(DownloadActivity.this).load(url).into(imageView);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

Above code will fetch the URL string from the edittext et and Glide library will download and show the image behind the URL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM