显示空白图像并且 onItemClick 不起作用

Blank image is shown and onItemClick wont work

我正在处理一个 Android 项目,其中我必须在列表中显示一些图像。为此,我正在使用适配器。当我 运行 代码时,我没有看到任何错误,但没有显示图像。另外,我在其中设置了一个 onClickListener 和一个 Log.d。但是 Log.d 没有显示。我做错了什么?

public class OtherUsers extends Activity {

    private PersonServiceImpl personService = new PersonServiceImpl();

    private static volatile List<RestPerson> restPersonList = new ArrayList<>();

    public static final String firstName = "firstname";
    public static final String userImage = "userimage";

    static final String userId = "0";
    ListView listView;
    UserAdapter userAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.displayuserlist);

        restPersonList = this.personService.getOtherUsers();

        ArrayList<HashMap<String, String>> usersArrayHashList = new ArrayList<>();
        for (RestPerson restPerson : restPersonList) {
            HashMap<String, String> restDisplay = new HashMap<>();
            restDisplay.put(userId, String.valueOf(restPerson.getUserId()));
            restDisplay.put(firstName, restPerson.getFirstName());
            restDisplay.put(userImage, restPerson.getProfilePhoto());
            usersArrayHashList.add(restDisplay);
        }

        listView = (ListView) findViewById(R.id.usersdisplaylist);

        userAdapter = new UserAdapter(this, usersArrayHashList);

        listView.setAdapter(userAdapter);

       listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Log.d("Item", "wasclicked");
                Long userid = restPersonList.get(position).getUserId();
                Log.d("Userid is ", String.valueOf(userid));
            }
        });
    }
}

适配器class:

public class UserAdapter extends BaseAdapter {

    private Activity activity;
    private ArrayList<HashMap<String, String>> data;
    private static LayoutInflater inflater = null;

    public UserAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
        activity = a;
        data = d;
        inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (convertView == null)
            view = inflater.inflate(R.layout.userprofiles, null);

        TextView username = (TextView) view.findViewById(R.id.userName);
        ImageView userImage = (ImageView) view.findViewById(R.id.userImage);
        HashMap<String, String> usersList = new HashMap<>();
        usersList = data.get(position);
        username.setText(usersList.get(OtherUsers.firstName));
        byte [] encodeByte=Base64.decode(usersList.get(OtherUsers.userImage).getBytes(), Base64.DEFAULT);
        Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
        userImage.setImageBitmap(bitmap);

        return view;
    }
}

看不到图片,在 Log.d 中看不到点击的 ID。不幸的是,没有错误可以诊断出什么问题。

更新

userprofiles.xml :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="5dip" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="15dp"
        android:orientation="vertical"
        android:weightSum="1">
        <ImageView
            android:id="@+id/userImage"
            android:layout_width="140dp"
            android:layout_height="200dp"
            android:scaleType="fitXY"
            android:padding="5dp"
            android:src="@drawable/profile"
            />

        <TextView
            android:id="@+id/userName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="visible"
            android:gravity="center"
            android:layout_gravity="center_horizontal|top"
            android:maxLines="1"
            android:ellipsize="end"
            android:scrollHorizontally="true"
            android:layout_marginTop="10dp"
            android:layout_weight="1.10" />
    </LinearLayout>
</RelativeLayout>

照片保存代码:

public class AddPhotoForUser extends Activity {

    private static final int CAMERA_PIC_REQUEST = 22;
    Button BtnSelectImage;
    private ImageView ImgPhoto;
    private static volatile Bitmap photo;
    private static volatile ByteArrayOutputStream stream = new ByteArrayOutputStream();

    final PersonServiceImpl personService = new PersonServiceImpl();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.upload_user_photo);
        Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
        uploadImageButton.setVisibility(View.INVISIBLE);

        ImgPhoto = (ImageView) findViewById(R.id.userPhotoImageView);
        BtnSelectImage = (Button) findViewById(R.id.userPhotoButtonSelect);
        BtnSelectImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {

                    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);

                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "Couldn't load photo", Toast.LENGTH_LONG).show();
                }
            }
        });


        uploadImageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!(v == null)) {
                    uploadImage();

                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Intent intent = new Intent(AddPhotoForUser.this, RestaurantList.class);
                    startActivity(intent);
                    finish();

                }
            }
        });

    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(AddPhotoForUser.this, Login.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onActivityResult(final int requestCode, int resultCode, Intent data) {
        try {
            switch (requestCode) {
                case CAMERA_PIC_REQUEST:
                    if (resultCode == RESULT_OK) {
                        try {
                            photo = (Bitmap) data.getExtras().get("data");
                            if (!(photo == null)) {
                                ImgPhoto.setImageBitmap(photo);
                                Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
                                uploadImageButton.setVisibility(View.VISIBLE);

                            }
                        } catch (Exception e) {
                            Toast.makeText(this, "Couldn't load photo", Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private void uploadImage() {

        if (!(photo == null)) {
            photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();
            personService.addUserProfilePhoto(Base64.encodeToString(byteArray, Base64.DEFAULT));
        }

    }
}

现在,调用方法将其保存在数据库中。目前因为byte-array骚扰的比较多,所以改成了String。 这是它现在在数据库中的样子:

ImlWQk9SdzBLR2dvQUFBQU5TVWhFVWdBQUFLQUFBQUI0Q0FJQUFBRDZ3RzQ0QUFBQUEzTkNTVlFJ
Q0FqYjRVL2dBQUFDZlVsRVFWUjRcbm5PM2RNWkxTWUJpQTRlOTNNcE40QmtvT29CVjBNTE9sVmg1
Q08rZ292SUUxV0ducEFUekMxcFI2QnpydHRXSUx0akpqTmo4a0pMejdcblB1V1NmUG1YZDhqT0xB
bWt6V1lURWJ2ZExuS3NWcXVzN1owLzFQd1hXWE4xY3d3TVoyQzRvbytoNzc1KytmY25WWmszb2pi
aGlTTldcblpVVGMvZm1iZDVSbndGY3dYSnBPcHhFeG44K3pkdHZ2OXcyUGZ2djk2NkpGbmV2em03
Y3R0MnhlZjEyM3o4ODE1eGVId3lFaUpwTkpcbjFnRk9lLzFYN2dtNUkrMS9peWZXZjhIa3NjMzNG
QTFuWURnRHd4a1l6c0J3Qm9Zek1KeUI0UXdNWjJBNEE4TVpHTTdBY0FhR1M0dkZcbklpSlNTbG03
SFkvSGhrYy8vZnh4MGFMTzlmSFY2NVpiTnErL3J0dm41NXJ6aTlOYnpSMWZ0amxRNFBadmc0L25z
dGErNTN1S2hqTXdcbm5JSGhEQXhuWURnRHd4a1l6c0J3Qm9Zek1KeUI0UXdNWjJBNEE4UDFjL3Zv
UUx4OXRDNlZaUmtSNi9VNjZ3RGI3YmJoMGZ1WFZkYTBcbnJueC8vNkhsbHMzcnIrdjIrYm5tL0NM
M1dvS1Q4L1lhajc3WFA1NzUvZzJHTXpDY2dlRjYrWnlzK3VkVmplY2l0T2ZHVnpDY2dlRU1cbkRH
ZGdPQVBER1JqT3dIQUdoak13bklIaGl0TS8rVzczL2xmbk4vTVZER2RnT0FQREdSak93SEFHaGpN
d25JSGhEQXhuWURnRHd4a1lcbnpzQndCb1o3dkxNaDkvT05jemwvcVBtOWZFRjBuZk9IbW4rbE8v
eWRQOVI4L3diREdSak93SEFHaGpNd25JSGhEQXhuWURnRHd4a1lcbnpzQndCb1l6TUp5QjRkSnl1
WXd4ZmFHeDg3dWRYOHhtczdqbEc1eWQzOHhUTkp5QjRRd01aMkE0QThNWkdNN0FjQWFHTXpDY2dl
RU1cbkRHZGdPQVBER1JqTzIwZmg4MU5WVlRHbTl5K2QzKzE4VDlGd0JvWXpNSnlCNFF3TVoyQTRB
OE1aR003QWNBYUdNekNjZ2VFTURHZGdcbk9BUERQUUE2L2ZhYjNyY3BjQUFBQUFCSlJVNUVya0pn
Z2c9PVxuIg==

以下方法用于添加照片和从服务器检索用户:

  @Override
    public void addUserProfilePhoto(final String profilePhoto) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    RestTemplate restTemplate = new RestTemplate();
                    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
                    HttpHeaders headers = new HttpHeaders();
                    headers.add("Cookie", "JSESSIONID=" + StaticRestTemplate.jsessionid);
                    //   headers.setContentType(MediaType.APPLICATION_JSON);
                    HttpEntity<String> entity = new HttpEntity<String>(profilePhoto, headers);
                    ResponseEntity<Boolean> out = restTemplate.exchange(addPhotoUrl, HttpMethod.POST, entity, Boolean.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<RestPerson> getOtherUsers() {
        final RestTemplate restTemplate = StaticRestTemplate.getRest();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                HttpHeaders requestHeaders = new HttpHeaders();
                requestHeaders.add("Cookie", "JSESSIONID=" + StaticRestTemplate.jsessionid);
                requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "json")));
                HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
                restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
                responseEntity = restTemplate.exchange(getOtherusers, HttpMethod.GET, requestEntity, RestPerson[].class);
            }
        });
        thread.start();
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        RestPerson[] restPersonsArray = responseEntity.getBody();
        List<RestPerson> restPersonArrayList = new ArrayList<>();
        Collections.addAll(restPersonArrayList, restPersonsArray);
        return restPersonArrayList;
    }

首先,您在这里设置了两次图像位图:

userImage.setImageBitmap(bitmap);
userImage.setImageBitmap(null);

确保删除最后一行,它将图像位图设置为空。

关于 onItemClickListener,确保清除 logcat 过滤文本,selected 日志级别进行调试,select 选项 "No filters" 而不是 "Show only selected Application" 只是为了确保您没有过滤掉您的日志。

检查restPersonList的计数是否等于0,并添加一个登录方法getView。

确保您已设置 android:descendantFocusability="blocksDescendants" 在你的 R.layout.userprofiles 中。 这可以防止行定义中的其他可聚焦或可点击项目拦截行点击。

其次,尝试为您的 imageview 设置背景颜色,并确保此 "colored" 视图是否真的可见。

编辑 最后,您在适配器 class 上的 getItem 是错误的:您必须 return data.get(position)