имя пустое - пользовательский ArrayAdapter - PullRequest
0 голосов
/ 04 ноября 2018

У меня есть пользовательский ArrayAdapter, который должен отображать изображение профиля пользователя и имя пользователя.

Я следовал этому уроку:

Пользовательские макеты Android с вашим собственным ArrayAdapter

Тем не менее, когда я открываю свою активность, приложение вылетает и говорит:

    java.lang.NullPointerException: name is null

Что верно, поскольку мне еще предстоит создать функцию, позволяющую пользователям добавить ее. Вместо этого должно отображаться изображение заполнителя. (Пикассо)

Вот мой CustomAdapter:

public class ContactsAdapter extends ArrayAdapter<CustomContact>{

private Context context;
private List<CustomContact> contactList;

//constructor, call on creation
public ContactsAdapter(Context context, int resource, ArrayList<CustomContact> objects) {
    super(context, resource, objects);

    this.context = context;
    this.contactList = objects;

}

public View getView(int position, View convertView, ViewGroup parent) {
    //get the user we are displaying
    CustomContact customcontact = contactList.get(position);

    //get the inflater and inflate the XML layout for each item
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.mylist, null);



    ImageView image = (ImageView) view.findViewById(R.id.friend_icon2);
    TextView friend_name = (TextView) view.findViewById(R.id.Itemname);

    //get & set username
    String completeUsername = customcontact.getUsername();
    friend_name.setText(completeUsername);

    //get the image associated with this user
    int imageID = context.getResources().getIdentifier(customcontact.getImageURL(), "string", context.getPackageName());

    //set image
    Picasso.get().load(imageID).placeholder(R.drawable.placeholder_image).resize(96, 96)
            .centerCrop().into(image);


    return view;
    }

}

Эта строка, возвращающая ноль, определяет ImageID:

//get the image associated with this user
    int imageID = context.getResources().getIdentifier(customcontact.getImageURL(), "string", context.getPackageName());

Вот мой ContactsActivity.java

public class ContactsActivity extends ListActivity {
private DatabaseReference mFriendDatabase;
private DatabaseReference mRootRef;
private DatabaseReference mUsersDatabase;
private FirebaseAuth mAuth;
private String mCurrent_user_id;
private View mMainView;
private RecyclerView mFriendsList;
private ListView contacts_list, lstView;
private ArrayAdapter dataAdapter;
private RelativeLayout individual_contact;



protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_contacts);

    ArrayList<CustomContact> contactList = new ArrayList<>();
    ArrayAdapter<CustomContact> adapter = new ContactsAdapter(ContactsActivity.this, 0, contactList);

    mAuth = FirebaseAuth.getInstance();
    mRootRef = FirebaseDatabase.getInstance().getReference();
    mCurrent_user_id = mAuth.getCurrentUser().getUid();
    mFriendDatabase = FirebaseDatabase.getInstance().getReference().child("friends").child(mCurrent_user_id);
    mFriendDatabase.keepSynced(true);

    contacts_list = (ListView) findViewById(android.R.id.list);
    contacts_list.setAdapter(adapter);
    individual_contact = (RelativeLayout) findViewById(R.id.mylist);


    DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference().child("users");







    usersRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot friendKeySnapshot: dataSnapshot.getChildren()) {
                String friendKey = friendKeySnapshot.getKey();



                usersRef.child(friendKey).addListenerForSingleValueEvent(new ValueEventListener() {

                    @Override
                    public void onDataChange(DataSnapshot friendSnapshot) {
                        String friendName = friendSnapshot.child("username").getValue(String.class);
                        String friendPicture = friendSnapshot.child("image_url").getValue(String.class);
                        contactList.add(
                                new CustomContact(friendName, friendPicture)
                        );

                        contacts_list.setAdapter(adapter);

                        //add event listener so we can handle clicks
                        AdapterView.OnItemClickListener adapterViewListener = new AdapterView.OnItemClickListener() {

                            //on click
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                                CustomContact customContact = contactList.get(position);

                                Intent intent = new Intent(ContactsActivity.this, MessageActivity.class);
                                intent.putExtra("username", customContact.getUsername());
                                intent.putExtra("ImageURL", customContact.getImageURL());

                                startActivity(intent);
                            }
                        };
                        //set the listener to the list view
                        contacts_list.setOnItemClickListener(adapterViewListener);



                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                        throw databaseError.toException();
                    }
                });
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            throw databaseError.toException();
        }
    });
}

}

1 Ответ

0 голосов
/ 04 ноября 2018

Чтобы установить изображение с помощью Picasso, вам нужно указать URL-адрес изображения в качестве параметра в методе load (), но вы вводите целочисленный идентификатор. Вы можете попробовать это

    Picasso.get().load(customcontact.getImageURL()).placeholder(R.drawable.placeholder_image).resize(96, 96)
        .centerCrop().into(image);

Пожалуйста, предоставьте ваши коды ContactsActivity.java для дальнейшего уточнения.

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