Исключение нулевого указателя Java при использовании Async Task для отложенной загрузки изображений - PullRequest
1 голос
/ 07 февраля 2012

Я пытался использовать AsyncTask для отложенной загрузки изображений в адаптер.

        public View getView(final int position,View convertView,ViewGroup parent){

    Bitmap userAvatarStream = null,podIconStream = null ;
    Bitmap podIconStream1 = null;
    Bitmap podIconStream2 = null;

    View v = convertView;

    if (v == null){
        LayoutInflater li = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = li.inflate(R.layout.user_list_item,null);

    }

 user = users.get(position);    


    if(user != null){

        URL userImageURL,podImageURL = null;

        //TextView tk = (TextView)v.findViewById(R.id.text_key);
        TextView firstname = (TextView)v.findViewById(R.id.follower_fullname);
        ImageView user_avatar = (ImageView)v.findViewById(R.id.follower_user_avatar);

        new LoadImage(user_avatar).execute(); 

TextView userProfileClick = (TextView) v.findViewById (R.id.follower_fullname);

        userProfileClick.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                String uID = user.getID();


                //Pass User id to another Intent(UserProfile)
                Intent userIntent = new Intent(activity,UserProfileMainActivity.class);
                userIntent.putExtra("userID",uID);
                activity.startActivity(userIntent);

            }
            });         

        ListView podlist = (ListView)v.findViewById(R.id.user_list); 

        ArrayList<Cr> List = new ArrayList<Cr>();

        for(Crb c : user.crList){
            List.add(c);
        }


        //new LoadImage(user_avatar).execute(); 
        UserFollowingPodListAdapter podadapter = new UserFollowingPodListAdapter(activity, R.layout.user_crumbs_pod_list_item,crumbsUpList,activity);
        podlist.setAdapter(podadapter);

    }
    return v;
} 

class LoadImage extends AsyncTask<String, Void, String>{

    private ImageView imv;
    private String path;
Bitmap userAvatarStream = null ;
final Bitmap podIconStream = null;

ProgressDialog dialog;

    @Override 
    protected void onPreExecute(){
        //Setting all the variables by getting the ids from the layout


    return;

    }


    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub


        URL userImageURL,podImageURL = null;

        try {
            userImageURL = new URL(user.imageUrl);
            if (user == null)
                return null;
            userAvatarStream = BitmapFactory.decodeStream(userImageURL.openConnection().getInputStream());
            if (userAvatarStream == null)
                return null;




        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

     @Override

     protected void onPostExecute(String result){
         user_avatar.setImageBitmap(userAvatarStream);

         return;

     }

}

}

Я получил исключение Java Null Poitner вonPostExecute.

Я отладил код, и userAvatarStream не является нулевым.Попробовал if / else, попытался / поймал, пытаясь выяснить, где происходит исключение NULL, и выяснил, где: user_avatar.setImageBitmap (userAvatarStream);Но не знаю, почему это происходит или как это удалить.Любая помощь будет высоко ценится.

Редактировать:

TextView firstname = (TextView)v.findViewById(R.id.follower_fullname);
            ImageView user_avatar = (ImageView)v.findViewById(R.id.follower_user_avatar);

1 Ответ

1 голос
/ 07 февраля 2012

По соглашению с комментаторами вам нужно создать экземпляр user_avatar, чтобы его можно было использовать.Вы открываете поток, чтобы вытянуть аватар, но на самом деле никогда ничего с ним не делаете.

Редактировать:

View v = LayoutInflater.from(context).inflate(R.layout.mybigdamnlayout, null);

Используйте это через SystemService.Это намного эффективнее (под эффективностью я имею в виду, что у меня никогда не было NPE таким образом).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...