显示空白图像,onItemClick不起作用

时间:2015-08-24 12:24:51

标签: java android baseadapter

我正在开发一个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));
            }
        });
    }
}

适配器类:

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>

PhotoSaving代码:

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));
        }

    }
}

现在,这会调用方法将其保存在DB中。目前,由于字节数组骚扰如此之多,我已将其更改为String。 以下是DB现在的样子:

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;
    }

2 个答案:

答案 0 :(得分:1)

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

其次,尝试为您的imageview设置背景颜色,并且这个“彩色”视图真的可见或不可见。

修改 最后你的适配器类上的getItem是错误的:你必须返回data.get(position)

答案 1 :(得分:0)

检查restPersonList的计数是否等于0,并在方法getView中添加一个日志。