繁体   English   中英

当我尝试在另一个活动中的imageview上显示图像时,应用程序崩溃

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

我正在开发一个基本上可以让用户在编辑文本中输入URL和标题的应用程序,然后按下下载按钮,该图像将显示在另一个活动中。 还有一些其他功能现在不相关。 我遇到的问题是,当我输入应显示已下载图像的imageview的id并按download下载图像时,应用崩溃。 到目前为止,这是我的代码:

主要活动:

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);
    }
}

主要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是我尝试显示图像的地方:

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是从以下位置下载映像的位置:

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();
            }
        }
    }
}

下载活动的代码是从这里获取的

下载活动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>

我会很感激的。

编辑:这是我现在的DownloadActivity,但仍不会在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

在API级别1中添加

public final void runOnUiThread(可运行操作)在UI线程上运行指定的操作。 如果当前线程是UI线程,则立即执行该操作。 如果当前线程不是UI线程,则将操作发布到UI线程的事件队列。

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();
                                                    }
                         }
    });

编辑2

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

请在onCreate()中初始化;

用。。。来代替

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();
            }
        }
    });
}

我将imageview的ID更改为ViewActivity中的ID时出现错误

因为您只能通过为该当前Activity的setContentView定义的布局运行findViewById来查找视图。

当您打开一个新的活动时,您将无法访问其显示的视图,因此,您将无法找到/使​​用它们。


在ViewActivity中,我建议仅使用Picasso或Glide库从URL加载图像并加载到R.id.pic而无需执行单独的Activity ...如果您确实想要单独的类,则可以查看“无头碎片”

使用较少的代码行就可以很容易地做到这一点。 首先,在MainActivity中,从用户处获取图像的URL,然后使用bundleintent将其传递给DownloadActivity 像这样:

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

这是将字符串url发送到DownloadActivity

在下载活动中,只需获取捆绑包并使用glide库,就可以从url中获取图像并加载到imageview 像这样 :

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

记住要在您的应用程序级别build.gradle添加glide库,如下所示:

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

更新1:

如果要将数据从一个活动发送到另一个活动,请使用上述方法。 如果获取URL并在同一活动中显示图像,请执行以下步骤:

在您的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();
            }
        }
    });

上面的代码将从edittext et中获取URL字符串,Glide库将下载并在URL后面显示图像。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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