2017-02-16 27 views
1

我試圖從我的RecyclerAdapter使用異步任務,但出於某種原因,我收到此錯誤:「java.lang.NullPointerException:嘗試調用虛擬方法'android.view。查看android.view.View.findViewById(INT)」對空對象引用」使用異步任務從RecyclerAdapter時出錯

這裏是我的代碼:

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> 
+0

請問您可以粘貼您的代碼佈局R.layout.card_layout? – noahutz

+0

@noahutz我剛加了它 –

+0

請看下面的答案。 – noahutz

回答

1

在行:

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

您可以訪問變量視圖,但是在您的代碼中您從未設置它。 所以它是空的。

另外,AsyncTasks有點難以正確,它可能會在您的活動已被殺死時結束。我推薦閱讀this answer given here

+0

你的意思是我沒有設置它? –

+0

我的Asynctasks完美工作,我試過這個代碼。謝謝 –

0

我覺得你沒有明白我的觀點。你的下載邏輯很好,但問題出在圖像視圖。您正在嘗試在啓動無法完成的活動(活動顯示)之前設置圖像視圖。以下是您需要做的事情:

  1. 在onclick開始您的活動顯示活動。
  2. 一旦顯示活動開始,然後執行下載邏輯。
  3. 用下載的圖像設置圖像視圖。
0

這裏的問題是您的代碼正在尋找您正在使用的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>