1

I"m trying to use async task from my RecyclerAdapter but for some reason, I'm getting this error: " java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference".

Here's my code:

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>
makkhay gurung
  • 528
  • 1
  • 4
  • 15

3 Answers3

1

In the line:

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

You access the variable view, but in your code you never set it. So it is null.

Also, AsyncTasks are kind of hard to get right, it might finish when your activity is already killed. I recommend reading this answer given here.

Community
  • 1
  • 1
Cubicle257
  • 335
  • 3
  • 14
0

I think you didn't get my point. Your download logic is fine but the problem is with the image view. you are trying to set image view before starting the activity(Activity display) which can't be done. Here is what you will have to do:

  1. In onclick start your activity display activity.
  2. Once display activity starts then perform the download logic.
  3. Set the image view with the downloaded image.
0

The problem here is your code is looking for the imageView inside the card_layout.xml layout you are using. You can fix this by inserting an ImageView with imageView id shown below. From there you can fix your layout.

<?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>
noahutz
  • 1,207
  • 1
  • 9
  • 11