0

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();
            }
        }
    });
frashid99
  • 9
  • 2
  • 1
    please attach error log – Ashvin solanki Nov 04 '18 at 06:07
  • Welcome to stack-overflow sir, please once visit https://stackoverflow.com/help/how-to-ask – Ashvin solanki Nov 04 '18 at 06:09
  • You can do `findViewById(R.id.test);` outside of the AsyncTask, but you should really be using Picasso or Glide libraries to download images from external sources – OneCricketeer Nov 04 '18 at 06:17
  • you have to use intent to first go to view activty and then show the image there by accessing the downloaded file via its path on phone, you can't use findviewbyid when you didn't inflate the parent view – masoud vali Nov 04 '18 at 06:23

3 Answers3

1

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();
            }
        }
    });
}
Community
  • 1
  • 1
Ashvin solanki
  • 4,802
  • 3
  • 25
  • 65
0

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"

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
0

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.

  • I have to get the url from the downloadactivity not the main one as it is part of the assignment. How would I do this by getting the url from download activity? – frashid99 Nov 05 '18 at 02:17
  • I also need to save the image to local storage. – frashid99 Nov 05 '18 at 04:09
  • I have updated my answer. Please check. If you want to store the image locally, you can find more info in this SO question : https://stackoverflow.com/questions/10388666/how-can-i-save-an-image-from-a-url/42317341 – Karthic Srinivasan Nov 05 '18 at 08:24
  • for the line Glide.with(DownloadActivity.this).load(url).into(imageView); I am getting an error "cannot resolve symbol 'imageview'". How do I fix this I cannot find anything online. – frashid99 Nov 06 '18 at 03:21
  • This is the code I have come up with but the picture still does not show up on ViewActivity. I have put the code in an edit above. – frashid99 Nov 06 '18 at 04:34
  • Id of your imageview is `test` as you mentioned in this line - `android:id="@+id/test`. But you are finding for the `imageview` with the id `pic` in this line - `pic = (ImageView) findViewById(R.id.pic);` This will obviously not work. Just change this line `pic = (ImageView) findViewById(R.id.pic);` to `ImageView pic = findViewById(R.id.test);` – Karthic Srinivasan Nov 06 '18 at 05:19