【问题标题】:Error while using Async task from RecyclerAdapter使用 RecyclerAdapter 的异步任务时出错
【发布时间】:2017-02-16 02:29:57
【问题描述】:

我正在尝试使用 RecyclerAdapter 中的异步任务,但由于某种原因,我收到此错误:“ java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.空对象引用上的 findViewById(int)'。

这是我的代码:

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
    Context c;
    ImageView img;
    View view;



    private String[] titles = {"One",
            "Two",
            "Three",
            "Four",
            "Five",
            "Six",
            "Seven",
            "Eight"};

    class ViewHolder extends RecyclerView.ViewHolder{



        public TextView itemTitle;



        public ViewHolder(View itemView) {
            super(itemView);

            itemTitle = (TextView)itemView.findViewById(R.id.item_title);


            itemView.setOnClickListener(new View.OnClickListener() {
                @Override public void onClick(View v) {
                    int position = getAdapterPosition();

                    String urlString;
                    switch( position) {
                        case 0:
                            Intent i = new Intent(v.getContext(),DisplayPicture.class);
                            v.getContext().startActivity(i);
                            urlString = "http://image-cdn.neatoshop.com/styleimg/36217/none/black/default/301347-19.jpg?v=b";
                            break;
                        case 1:
                            urlString = c.getResources().getString(R.string.chuck_http);
                            break;
                        case 2:
                            urlString = c.getResources().getString(R.string.app_name);
                            break;
                        case 3:
                            urlString = c.getResources().getString(R.string.mrt_http);
                            break;
                        case 4:
                            urlString = c.getResources().getString(R.string.faceman_http);
                            break;
                        case 5:
                            urlString = c.getResources().getString(R.string.knight_http);
                            break;
                        default:
                            urlString = c.getResources().getString(R.string.chuck_http);
                    }
                    new DownloadImageTask().execute(urlString);



                }
            });
        }
    }

    // Makes scrolling smooth
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.card_layout, viewGroup, false);
        ViewHolder viewHolder = new ViewHolder(v);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder viewHolder, int i) {
        viewHolder.itemTitle.setText(titles[i]);
    }

    @Override
    public int getItemCount() {
        return titles.length;
    }
    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        protected Bitmap doInBackground(String... urls) {
            return downloadImage(urls[0]);
        }
        protected  void onPostExecute(Bitmap bm) {

            img = (ImageView) view.findViewById(R.id.imageView);
            img.setImageBitmap(bm);
        }
    }

    private Bitmap downloadImage(String urlStr) {
        Bitmap bm = null;
        InputStream in = null;
        try {
            in = openHttpConnection(urlStr);
            bm = BitmapFactory.decodeStream(in);
            in.close();
        } catch (Exception ex) {
            Log.d("DL Image", ex.getLocalizedMessage());
        }
        return bm;
    }
    private InputStream openHttpConnection(String urlString) throws Exception {
        InputStream is = null;
        int res = -1;   // response
        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();
        if ( !(conn instanceof HttpURLConnection) ) {
            throw new IllegalArgumentException("Not an HttpURLConnection");
        }
        try {
            HttpURLConnection huc = (HttpURLConnection)conn;
            huc.setAllowUserInteraction(false);
            huc.setInstanceFollowRedirects(true);
            huc.setRequestMethod("GET");
            huc.connect();
            res = huc.getResponseCode();
            if ( res == HttpURLConnection.HTTP_OK ) {
                is = huc.getInputStream();
            }
        } catch ( Exception ex ) {
            Log.d("Networking", ex.getLocalizedMessage() );
            throw ex;
        }
        return is;
    }





}

card_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/card_view"
    android:layout_margin="5dp"
    card_view:cardBackgroundColor="#81C784"
    card_view:cardCornerRadius="12dp"
    card_view:cardElevation="3dp"
    card_view:contentPadding="4dp"
    android:foreground="?selectableItemBackground"
    android:clickable="true" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="16dp" >


        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/item_title"
            android:layout_alignParentTop="true"
            android:textSize="30sp"
            />


    </RelativeLayout>
</android.support.v7.widget.CardView>

【问题讨论】:

  • 你能粘贴你的布局R.layout.card_layout的代码吗?
  • @noahutz 我刚刚添加了它
  • 请看下面我的回答。

标签: java android android-studio


【解决方案1】:

行内:

img = (ImageView) view.findViewById(R.id.imageView);

您访问变量视图,但在您的代码中您从未设置它。 所以它是空的。

此外,AsyncTasks 有点难以正确处理,它可能会在您的活动已被终止时完成。我推荐阅读this answer given here

【讨论】:

  • 你的意思是我没有设置它?
  • 我的 Asynctasks 运行良好,我已经尝试过该代码。谢谢
【解决方案2】:

我想你没有明白我的意思。您的下载逻辑很好,但问题出在图像视图上。您正在尝试在无法完成的活动(活动显示)之前设置图像视图。以下是您必须做的:

  1. 在 onclick 中启动您的活动显示活动。
  2. 一旦显示活动开始,然后执行下载逻辑。
  3. 使用下载的图像设置图像视图。

【讨论】:

    【解决方案3】:

    这里的问题是您的代码正在您正在使用的 card_layout.xml 布局中寻找 imageView。您可以通过插入带有如下所示 imageView id 的 ImageView 来解决此问题。从那里你可以修复你的布局。

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v7.widget.CardView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/card_view"
        android:layout_margin="5dp"
        card_view:cardBackgroundColor="#81C784"
        card_view:cardCornerRadius="12dp"
        card_view:cardElevation="3dp"
        card_view:contentPadding="4dp"
        android:foreground="?selectableItemBackground"
        android:clickable="true" >
    
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="16dp" >
    
    
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/item_title"
                android:layout_alignParentTop="true"
                android:textSize="30sp"
                />
    
            <ImageView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:scaleType="fitXY"
                android:id="@+id/imageView"/>
    
    
        </RelativeLayout>
    </android.support.v7.widget.CardView>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多