Hello.

I want to add a download of a picture to RecyclerView from a URL, but I get:

 IllegalArgumentException: Target must not be null. 

Tell me, please, what is the problem.

 public class IdeaListRecycler extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{ SwipeRefreshLayout mSwipeRefreshLayout; public ArrayList<Product> products = new ArrayList<>(); private PersonAdapter mAdapter; //ссылка на вьюшку из представления private RecyclerView mRecyclerView; ImageView imageView2; public class ParseTask extends AsyncTask<Void, Void, String> { HttpURLConnection urlConnection = null; BufferedReader reader = null; String resultJson = ""; @Override protected String doInBackground(Void... params) { // получаем данные с внешнего ресурса try { URL url = new URL("http://malfurion.pythonanywhere.com/rest/get_ideas_list"); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { buffer.append(line); } resultJson = buffer.toString(); } catch (Exception e) { e.printStackTrace(); } return resultJson; } @Override protected void onPostExecute(String strJson) { super.onPostExecute(strJson); // выводим целиком полученную json-строку JSONObject dataJsonObj = null; String secondName = ""; try { dataJsonObj = new JSONObject(strJson); JSONArray friends = dataJsonObj.getJSONArray("data"); ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar); pb.setVisibility(View.INVISIBLE); mAdapter = new PersonAdapter(products,IdeaListRecycler.this); mRecyclerView.setAdapter(mAdapter); // 2. перебираем и выводим контакты каждого друга for (int i = 0; i < friends.length(); i++) { JSONObject friend = friends.getJSONObject(i); // JSONObject contacts = friend.getJSONObject("contacts"); String title = friend.getString("title"); String id = friend.getString("id"); String sdesc = friend.getString("short_description"); String description = friend.getString("description"); products.add(new Product(title, sdesc, id, description)); } } catch (JSONException e) { e.printStackTrace(); } } } //ссылка на адаптер, класс который знает всё о модели и дёргает методы холдера ParseTask ps; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_idea_list_recycler); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); imageView2 = (ImageView) findViewById(R.id.imageView2) ; DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView); //Назначаем вьюхе адаптером наш экземпляр PersonAdapter ps = new ParseTask(); ps.execute(); //LinearLayoutManager занимается размещением объектов на экране и прокруткой mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mRecyclerView.addOnItemTouchListener(new RecyclerClickListener(this) { @Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { } @Override public void onItemClick(RecyclerView recyclerView, View itemView, int position) { Intent intent = new Intent(IdeaListRecycler.this,IdeaPage.class); Log.d("mesage",products.get(1).title.toString() ); intent.putExtra("id",products.get(position).id); intent.putExtra("description",products.get(position).description); intent.putExtra("content",products.get(position).content); intent.putExtra("title",products.get(position).title); startActivity(intent); } }); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { Toast.makeText(this,"Нажмите кнопку домой для выхода из приложения",Toast.LENGTH_SHORT).show(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.idea_list_recycler, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //Кнопка обновить СПИСОК................................................ if (id == R.id.refreshMenu) { try { ParseTask nps = new ParseTask(); nps.execute(); } catch (Exception e){ e.printStackTrace(); } } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_camera) { // Handle the camera action } else if (id == R.id.nav_gallery) { } else if (id == R.id.nav_slideshow) { Intent vovchik = new Intent(this, ShareIdeaActivity.class); startActivity(vovchik); } else if (id == R.id.media_actions) { } else if (id == R.id.nav_share) { } else if (id == R.id.nav_send) { } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } private class PersonHolder extends RecyclerView.ViewHolder{ private TextView mPersonNameTextView; private TextView mPersonAdressTextView; private TextView mPersonSexTextView; private TextView mPersonAgeTextView; private Product mPerson; public PersonHolder(View itemView) { super(itemView); mPersonNameTextView = (TextView) itemView.findViewById(R.id.tvTitle); mPersonAdressTextView = (TextView) itemView.findViewById(R.id.tvSdesc); } //Метод, связывающий ранее добытые в конструкторе ссылки с данными модели public void bindCrime(Product person) { mPerson = person; mPersonNameTextView.setText(mPerson.title); mPersonAdressTextView.setText(mPerson.content); } } //Наш адаптер, мост между фабрикой клонов и выводом их на экран. //Его методы будет дёргать LinearLayoutManager, назныченный вьюшке //RecyclerView в методе onCreate нашей активити private class PersonAdapter extends RecyclerView.Adapter<PersonHolder> { private ArrayList<Product> mPersons; private Context mContext; public PersonAdapter(ArrayList<Product> persons, Context context) { mPersons = persons; mContext = context; } //Создаёт пустую вьюшку,оборачивает её в PersonHolder. //Дальше забота по наполнению этой вьюшки ложиться именно на объект PersonHolder'а @Override public PersonHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater li = getLayoutInflater(); View view = li.inflate(R.layout.list_item_person, parent, false); return new PersonHolder(view); } //Дёргает метод холдера при выводе нового элемента списка на экран, //передавая ему актуальный объект модели для разбора и представления @Override public void onBindViewHolder(PersonHolder holder, int position) { Product person = mPersons.get(position); Picasso.with(mContext).load("http://i.imgur.com/DvpvklR.png").into(imageView2); holder.bindCrime(person); } //Возвращает размер хранилища моделей @Override public int getItemCount() { return mPersons.size(); } } } 
  • You have imageView2 null. And that where you in it the picture - is extremely wrong. Probably you wanted to display it in the list box. - JuriySPb
  • I want to make so that the loaded image is displayed in each item of the list of recyclerview, imageview2 this is imageview on the layout of the item of the list. - j3texe

1 answer 1

The problem is that imageView2 , where you want to upload the image, is initialized to null .

To initialize the imageView2 field You are trying to onCreate(...) method:

 imageView2 = (ImageView) findViewById(R.id.imageView2) ; 

Why is imageView2 initialized to null ? - because in R.layout.activity_idea_list_recycler there is no representation with id imageView2 .

To upload an image to the RecyclerView element, you need:

  1. Add your R.layout.list_item_person to R.layout.list_item_person ;
  2. In PersonHolder declare a field of type ImageView , for example ImageView mImageView ;
  3. In the constructor of PersonHolder() initialize the mImageView field:

     mImageView = (ImageView) itemView.findViewById(R.id.imageView2); 
  4. In the onBindBiewHolder(...) method upload a picture:

     Picasso.with(mContext).load("http://i.imgur.com/DvpvklR.png").into(holder.mImageView); 

In general, it will be more correct to load an image in the bindCrime(...) ViewHolder method, if you have one.