0

I am working on an Android project in which I have to display some images in a list. For this, I am using an Adapter. I don't see any errors when I run the code, but no image is displayed. Also, I have set an onClickListener, and a Log.d inside it. But the Log.d is not displayed. What am I doing wrong?

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

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

No image is seen, cant see in Log.d the clicked id. Unfortunately no errors to diagnose whats wrong.

Update

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 code :

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

    }
}

Now , this calls the method to save it in DB. Currently, because byte-array was harassing so much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huWURnRHd4a1lcbnpzQndCb1l6TUp5QjRkSnl1
WXd4ZmFHeDg3dWRYOHhtczdqbEc1eWQzOHhUTkp5QjRRd01aMkE0QThNWkdNN0FjQWFHTXpDY2dl
RU1cbkRHZGdPQVBER1JqTzIwZmg4MU5WVlRHbTl5K2QzKzE4VDlGd0JvWXpNSnlCNFF3TVoyQTRB
OE1aR003QWNBYUdNekNjZ2VFTURHZGdcbk9BUERQUUE2L2ZhYjNyY3BjQUFBQUFCSlJVNUVya0pn
Z2c9PVxuIg==

Below methods are used to add photo and retrieve users from server :

  @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;
    }
kryger
  • 12,906
  • 8
  • 44
  • 65
We are Borg
  • 5,117
  • 17
  • 102
  • 225

3 Answers3

1

First thing, You set the image bitmap twice here:

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

make sure to remove the last line, which sets the image bitmap to null.

About the onItemClickListener, make sure you cleared the logcat filtering text, selected Log level to debug, and select the option "No filters" instead of "Show only selected Application" just to be sure you are not filtering out Your logs.

  • I removed that line, still no image. and when I click on the image, I get in Log when no filters are selected, 08-24 14:40:29.415 1221-1278/system_process W/AudioTrack﹕ AUDIO_OUTPUT_FLAG_FAST denied by client . – We are Borg Aug 24 '15 at 12:41
  • in order to make the `OnItemClickListener` work, make sure no views inside the row provided by your adapter has any `OnClickListener` set. Can you please post the contents of your `userprofiles.xml` file? – Andrzej Chmielewski Aug 24 '15 at 12:47
  • Pasted, can you please check. – We are Borg Aug 24 '15 at 12:48
  • make sure to remove the `weightSum` parameter from your linearLayout and remove `layout_weight` from the `TextView`, you can also try to, instead of setting the `OnItemClickListener` on listview, set the `OnClickListener` on `view`, just before `return view;` in your adapter – Andrzej Chmielewski Aug 24 '15 at 13:14
  • I did all what you said, except putting OnClickListener in adapter, when I do that, the entire click functionality just went away. No click action was intercepted. Unfortunately, I still don't have image. Shall I post the code of how I am saving the image? – We are Borg Aug 24 '15 at 13:21
  • After the changes, click is working now. Just image remaining. can you please check the updated post. – We are Borg Aug 24 '15 at 13:31
1

Ensure you have set android:descendantFocusability="blocksDescendants" in your R.layout.userprofiles. This prevent that other focusable or clickable item in your row definition intercept row click.

Secondly, try to set a background color to your imageview and very that this "colored" view is really visible or not.

Edit Finaly your getItem on adapter class is wrong: you have to return data.get(position)

christian mini
  • 1,662
  • 20
  • 39
  • Still nothing. I don't understand what is going wrong. – We are Borg Aug 24 '15 at 12:56
  • you must set android:descendantFocusability="blocksDescendants" on RelativeLayout in userprofile.xml. About imageview try to add android:layout_weight="1" – christian mini Aug 24 '15 at 13:05
  • Did that, no help. Shall I post the code of how I am saving image and retrieval? – We are Borg Aug 24 '15 at 13:22
  • Yes, if you post is usefull. Please try to set invisible your textview with android:visibility="gone" and tell me if you finally see your image. – christian mini Aug 24 '15 at 13:32
  • Nope, still no image, text is now gone because I selected gone, but I am seeing in the Log, --- SkImageDecoder::Factory returned null. I have posted how I am doing it. Kindly have a look. – We are Borg Aug 24 '15 at 13:34
  • your getItem defined on Adapter class is wrong: you have to return data.get(position) and not position. – christian mini Aug 24 '15 at 14:22
  • Changed it, seems like I have found the error, I have posted a new question : http://stackoverflow.com/questions/32184289/android-skimagedecoderfactory-returned-null-when-retrieving-complex-object – We are Borg Aug 24 '15 at 14:23
  • To set answer accepted check this link:http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work. – christian mini Aug 24 '15 at 14:32
0

Check if the count of restPersonList is equal to 0,and add a log in method getView。

simonws
  • 65
  • 5