我的活动课:

public class CommonChattingAttachmentActivity
        extends AppCompatActivity {

    Realm realm;
    RealmChangeListener realmChangeListener;
    CommonChattingAttachmentCustomAdapter adapter;
    ListView lv;
    EditText descEditTxt;
    boolean result = Utility.checkPermission(CommonChattingAttachmentActivity.this);
    String userChoosenTask;
    TextView descTxt;
    ImageView imgallery, imgcam, img;
    private static final int REQUEST_CAMERA = 1888;
    private static final int SELECT_FILE = 1889;
    ImageView imgattach;

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

        lv = (ListView) findViewById(R.id.Listview_common);
        //img=(ImageView)findViewById(R.id.img);
        //descTxt= (TextView) findViewById(R.id.textdesc);
        //INITIALIZE REALM
        realm = Realm.getDefaultInstance();
        setAdapter();
        displayInputDialog();
        imgcam = (ImageView) findViewById(R.id.imgcam);
        imgallery = (ImageView) findViewById(R.id.imggallery);
        imgattach = (ImageView) findViewById(R.id.imgattach);
        imgallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                galleryIntent();
            }
        });
        imgcam.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cameraIntent();
            }
        });
        imgattach.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectImage();
            }
        });

    }

    public void setAdapter() {
        //lv= (ListView) findViewById(R.id.Listview_common);
        final CommonChatRealmHelper helper = new CommonChatRealmHelper(realm);
        helper.retrieveFromDB();
        adapter = new CommonChattingAttachmentCustomAdapter(this, helper.justRefresh());
        lv.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        realmChangeListener = new RealmChangeListener() {
            @Override
            public void onChange() {
                adapter = new CommonChattingAttachmentCustomAdapter(CommonChattingAttachmentActivity.this, helper.justRefresh());
                lv.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }
        };
        realm.addChangeListener(realmChangeListener);
    }

    private void setAdapters() {
        lv = (ListView) findViewById(R.id.Listview_common);
        //INITIALIZE REALM
        realm = Realm.getDefaultInstance();
        final CommonChatRealmHelper helper = new CommonChatRealmHelper(realm);
        helper.retrieveFromDB();
        adapter = new CommonChattingAttachmentCustomAdapter(this, helper.justRefresh());
        lv.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        realmChangeListener = new RealmChangeListener() {
            @Override
            public void onChange() {
                adapter = new CommonChattingAttachmentCustomAdapter(CommonChattingAttachmentActivity.this, helper.justRefresh());
                lv.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }
        };
        realm.addChangeListener(realmChangeListener);
    }

    //DISPLAY INPUT DIALOG
    public void displayInputDialog() {

        //EDITTEXTS
        descEditTxt = (EditText) findViewById(R.id.editwrite);
        ImageView fab = (ImageView) findViewById(R.id.send);

        //SAVE
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // descTxt.setVisibility(View.VISIBLE);
                //img.setVisibility(View.GONE);
                String desc = descEditTxt.getText().toString();
                CommonChat s = new CommonChat();
                s.setDescription(desc);
                CommonChatRealmHelper helper = new CommonChatRealmHelper(realm);
                if(helper.save(s)) {
                    descEditTxt.setText("");

                } else {
                    Toast.makeText(CommonChattingAttachmentActivity.this, "Invalid Data", Toast.LENGTH_SHORT).show();
                }
            }


        });
    }

    public void cameraIntent() {
        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        // Intent intent = new Intent(MediaStore.EXTRA_OUTPUT);
        startActivityForResult(intent, REQUEST_CAMERA);
    }

    public void galleryIntent() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);//
        startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
    }

    public void selectImage() {
        final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};
        AlertDialog.Builder builder = new AlertDialog.Builder(CommonChattingAttachmentActivity.this);
        builder.setTitle("Add Photo!");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                boolean result = Utility.checkPermission(CommonChattingAttachmentActivity.this);
                if(items[item].equals("Take Photo")) {
                    userChoosenTask = "Take Photo";
                    if(result) {
                        cameraIntent();
                    }
                } else if(items[item].equals("Choose from Library")) {
                    userChoosenTask = "Choose from Library";
                    if(result) {
                        galleryIntent();
                    }
                } else if(items[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch(requestCode) {
            case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if(userChoosenTask.equals("Take Photo")) {
                        cameraIntent();
                    } else if(userChoosenTask.equals("Choose from Library")) {
                        galleryIntent();
                    }
                } else {
                    //code for deny
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode == Activity.RESULT_OK) {
            if(requestCode == SELECT_FILE) {
                onSelectFromGalleryResult(data);
            } else if(requestCode == REQUEST_CAMERA) {
                onCaptureImageResult(data);
            }

        }
    }

    @SuppressWarnings("deprecation")
    public void onSelectFromGalleryResult(Intent data) {

        Bitmap bm = null;
        if(data != null) {
            try {
                bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
            } catch(IOException e) {
                e.printStackTrace();
            }
        }
        SaveImageVideoData(String.valueOf(bm));
        setAdapters();
    }

    public void onCaptureImageResult(Intent data) {
        Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
        File destination = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
        FileOutputStream fo;
        try {
            destination.createNewFile();
            fo = new FileOutputStream(destination);
            fo.write(bytes.toByteArray());
            fo.close();
        } catch(FileNotFoundException e) {
            e.printStackTrace();
        } catch(IOException e) {
            e.printStackTrace();
        }
        SaveImageVideoData(String.valueOf(destination));
        setAdapters();
    }

    public void SaveImageVideoData(String data) {
        try {
            Realm realm = Realm.getDefaultInstance();
            realm.beginTransaction();
            CommonChat s = realm.createObject(CommonChat.class);
            // obj.setExtensionTypeValue(stringMediaExtType);
            s.setImageUrl(data);
            realm.commitTransaction();
            realm.close();
            setAdapters();
            Log.d("path", data);
            Log.d("working realm", "yes....");
        } catch(Exception ex) {
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        realm.removeChangeListener(realmChangeListener);
        realm.close();
    }
}


我的适配器类

public class CommonChattingAttachmentCustomAdapter
        extends BaseAdapter {

    Context c;
    ArrayList<CommonChat> CommonChats;

    public CommonChattingAttachmentCustomAdapter(Context c, ArrayList<CommonChat> CommonChats) {
        this.c = c;
        this.CommonChats = CommonChats;
    }

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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(convertView == null) {
            convertView = LayoutInflater.from(c).inflate(R.layout.item_commonchat, parent, false);
        }


        TextView descTxt = (TextView) convertView.findViewById(R.id.textdesc);
        ImageView img = (ImageView) convertView.findViewById(R.id.img);


        final CommonChat s = (CommonChat) this.getItem(position);

        if(descTxt != null) {
            descTxt.setVisibility(View.VISIBLE);
            img.setVisibility(View.GONE);
            descTxt.setText(s.getDescription());
        }


        String imageUrl = s.getImageUrl();

        if(imageUrl != null && imageUrl.length() > 0) {
            img.setVisibility(View.VISIBLE);
            descTxt.setVisibility(View.GONE);
            Picasso.with(c).load(imageUrl).placeholder(R.mipmap.ic_launcher).into(img);

        } else {

            Picasso.with(c).load(R.mipmap.ic_launcher).into(img);
        }
        return convertView;
    }
}


我的RealmHelper类:

 public class CommonChatRealmHelper {

    Realm realm;
    RealmResults<CommonChat> CommonChats;
    Boolean saved = null;

    public CommonChatRealmHelper(Realm realm) {
        this.realm = realm;
    }

    //WRITE
    public Boolean save(final CommonChat CommonChat) {
        if(CommonChat == null) {
            saved = false;
        } else {
            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {

                    try {
                        CommonChat s = realm.copyToRealm(CommonChat);

                        saved = true;

                    } catch(RealmException e) {
                        e.printStackTrace();
                        saved = false;
                    }

                }
            });
        }


        return saved;
    }

    //READ
    public void retrieveFromDB() {
        CommonChats = realm.where(CommonChat.class).findAll();
    }

    // REFRESH
    public ArrayList<CommonChat> justRefresh() {
        ArrayList<CommonChat> latest = new ArrayList<>();
        for(CommonChat s : CommonChats) {
            latest.add(s);
            Log.d("Testing", String.valueOf(s));
        }
        return latest;
    }
}



  Blockquote 10-06 10:46:40.735 24930-24930 / com.xitiz.xitizmobile D /测试:CommonChat = [{description:null},{imageUrl:/storage/emulated/0/1507267000613.jpg}]
  10-06 10:46:40.745 24930-24930 / com.xitiz.xitizmobile D /路径:/storage/emulated/0/1507267000613.jpg


 **My Edited Code Snippet of URI**

public class CommonChattingAttachmentActivity
        extends AppCompatActivity {

    Realm realm;
    RealmChangeListener realmChangeListener;
    CommonChattingAttachmentCustomAdapter adapter;
    ListView lv;
    EditText descEditTxt;
    boolean result = Utility.checkPermission(CommonChattingAttachmentActivity.this);
    String userChoosenTask;
    TextView descTxt;
    ImageView imgallery, imgcam, img;
    private static final int REQUEST_CAMERA = 1888;
    private static final int SELECT_FILE = 1889;
    ImageView imgattach;

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

        lv = (ListView) findViewById(R.id.Listview_common);
        //img=(ImageView)findViewById(R.id.img);
        //descTxt= (TextView) findViewById(R.id.textdesc);
        //INITIALIZE REALM
        realm = Realm.getDefaultInstance();
        setAdapter();
        displayInputDialog();
        imgcam = (ImageView) findViewById(R.id.imgcam);
        imgallery = (ImageView) findViewById(R.id.imggallery);
        imgattach = (ImageView) findViewById(R.id.imgattach);
        imgallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                galleryIntent();
            }
        });
        imgcam.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cameraIntent();
            }
        });
        imgattach.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectImage();
            }
        });

    }

    public void setAdapter() {
        //lv= (ListView) findViewById(R.id.Listview_common);
        final CommonChatRealmHelper helper = new CommonChatRealmHelper(realm);
        helper.retrieveFromDB();
        adapter = new CommonChattingAttachmentCustomAdapter(this, helper.justRefresh());
        lv.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        realmChangeListener = new RealmChangeListener() {
            @Override
            public void onChange() {
                adapter = new CommonChattingAttachmentCustomAdapter(CommonChattingAttachmentActivity.this, helper.justRefresh());
                lv.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }
        };
        realm.addChangeListener(realmChangeListener);
    }

    private void setAdapters() {
        lv = (ListView) findViewById(R.id.Listview_common);
        //INITIALIZE REALM
        realm = Realm.getDefaultInstance();
        final CommonChatRealmHelper helper = new CommonChatRealmHelper(realm);
        helper.retrieveFromDB();
        adapter = new CommonChattingAttachmentCustomAdapter(this, helper.justRefresh());
        lv.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        realmChangeListener = new RealmChangeListener() {
            @Override
            public void onChange() {
                adapter = new CommonChattingAttachmentCustomAdapter(CommonChattingAttachmentActivity.this, helper.justRefresh());
                lv.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }
        };
        realm.addChangeListener(realmChangeListener);
    }

    //DISPLAY INPUT DIALOG
    public void displayInputDialog() {

        //EDITTEXTS
        descEditTxt = (EditText) findViewById(R.id.editwrite);
        ImageView fab = (ImageView) findViewById(R.id.send);

        //SAVE
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // descTxt.setVisibility(View.VISIBLE);
                //img.setVisibility(View.GONE);
                String desc = descEditTxt.getText().toString();
                CommonChat s = new CommonChat();
                s.setDescription(desc);
                CommonChatRealmHelper helper = new CommonChatRealmHelper(realm);
                if(helper.save(s)) {
                    descEditTxt.setText("");

                } else {
                    Toast.makeText(CommonChattingAttachmentActivity.this, "Invalid Data", Toast.LENGTH_SHORT).show();
                }
            }


        });
    }

    public void cameraIntent() {
        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        // Intent intent = new Intent(MediaStore.EXTRA_OUTPUT);
        startActivityForResult(intent, REQUEST_CAMERA);
    }

    public void galleryIntent() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);//
        startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
    }

    public void selectImage() {
        final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};
        AlertDialog.Builder builder = new AlertDialog.Builder(CommonChattingAttachmentActivity.this);
        builder.setTitle("Add Photo!");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                boolean result = Utility.checkPermission(CommonChattingAttachmentActivity.this);
                if(items[item].equals("Take Photo")) {
                    userChoosenTask = "Take Photo";
                    if(result) {
                        cameraIntent();
                    }
                } else if(items[item].equals("Choose from Library")) {
                    userChoosenTask = "Choose from Library";
                    if(result) {
                        galleryIntent();
                    }
                } else if(items[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch(requestCode) {
            case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if(userChoosenTask.equals("Take Photo")) {
                        cameraIntent();
                    } else if(userChoosenTask.equals("Choose from Library")) {
                        galleryIntent();
                    }
                } else {
                    //code for deny
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode == Activity.RESULT_OK) {
            if(requestCode == SELECT_FILE) {
                onSelectFromGalleryResult(data);
            } else if(requestCode == REQUEST_CAMERA) {
                onCaptureImageResult(data);
            }

        }
    }

    @SuppressWarnings("deprecation")
    public void onSelectFromGalleryResult(Intent data) {

        Bitmap bm = null;
        if(data != null) {
            try {
                bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
            } catch(IOException e) {
                e.printStackTrace();
            }
        }
        Uri myUri = Uri.parse(String.valueOf(bm));
        SaveImageVideoData(String.valueOf(myUri));


        // setAdapters();
    }

    public void onCaptureImageResult(Intent data) {
        Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
        File destination = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
        FileOutputStream fo;
        try {
            destination.createNewFile();
            fo = new FileOutputStream(destination);
            fo.write(bytes.toByteArray());
            fo.close();
        } catch(FileNotFoundException e) {
            e.printStackTrace();
        } catch(IOException e) {
            e.printStackTrace();
        }
        // SaveImageVideoData(String.valueOf(destination));
        // setAdapters();
        Uri myUri = Uri.parse(String.valueOf(destination));
        SaveImageVideoData(String.valueOf(myUri));
    }

    public void SaveImageVideoData(String data) {
        try {
            Realm realm = Realm.getDefaultInstance();
            realm.beginTransaction();
            CommonChat s = realm.createObject(CommonChat.class);
            // obj.setExtensionTypeValue(stringMediaExtType);
            s.setImageUrl(data);
            realm.commitTransaction();
            realm.close();
            setAdapters();
            Log.d("path", data);
            Log.d("working realm", "yes....");
        } catch(Exception ex) {
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        realm.removeChangeListener(realmChangeListener);
        realm.close();
    }
}

最佳答案

代替此代码

public class CommonChattingAttachmentActivity
        extends AppCompatActivity {

    Realm realm;
    //RealmChangeListener realmChangeListener;
    CommonChattingAttachmentCustomAdapter adapter;
    ListView lv;
    EditText descEditTxt;
    boolean result = Utility.checkPermission(CommonChattingAttachmentActivity.this);
    String userChoosenTask;
    TextView descTxt;
    ImageView imgallery, imgcam, img;
    private static final int REQUEST_CAMERA = 1888;
    private static final int SELECT_FILE = 1889;
    ImageView imgattach;

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

        lv = (ListView) findViewById(R.id.Listview_common);
        //img=(ImageView)findViewById(R.id.img);
        //descTxt= (TextView) findViewById(R.id.textdesc);
        //INITIALIZE REALM
        realm = Realm.getDefaultInstance();
        setAdapter();
        displayInputDialog();
        imgcam = (ImageView) findViewById(R.id.imgcam);
        imgallery = (ImageView) findViewById(R.id.imggallery);
        imgattach = (ImageView) findViewById(R.id.imgattach);
        imgallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                galleryIntent();
            }
        });
        imgcam.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cameraIntent();
            }
        });
        imgattach.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectImage();
            }
        });

    }

    public void setAdapter() {
        //lv= (ListView) findViewById(R.id.Listview_common);
        //final CommonChatRealmHelper helper = new CommonChatRealmHelper(realm);
        //helper.retrieveFromDB();
        //adapter = new CommonChattingAttachmentCustomAdapter(this, helper.justRefresh());
        lv.setAdapter(adapter);
        //adapter.notifyDataSetChanged();
        //realmChangeListener = new RealmChangeListener() {
        //    @Override
        //    public void onChange() {
        //        adapter = new CommonChattingAttachmentCustomAdapter(CommonChattingAttachmentActivity.this, helper.justRefresh());
       //         lv.setAdapter(adapter);
       //         adapter.notifyDataSetChanged();
       //     }
       // };
       // realm.addChangeListener(realmChangeListener);
    }

    private void setAdapters() {
        lv = (ListView) findViewById(R.id.Listview_common);
        //INITIALIZE REALM
       // realm = Realm.getDefaultInstance();
        //final CommonChatRealmHelper helper = new CommonChatRealmHelper(realm);
       // helper.retrieveFromDB();
       // adapter = new CommonChattingAttachmentCustomAdapter(this, helper.justRefresh());
        lv.setAdapter(adapter);
       // adapter.notifyDataSetChanged();
       // realmChangeListener = new RealmChangeListener() {
        //    @Override
       //     public void onChange() {
        //        adapter = new CommonChattingAttachmentCustomAdapter(CommonChattingAttachmentActivity.this, helper.justRefresh());
        //        lv.setAdapter(adapter);
        //        adapter.notifyDataSetChanged();
        //    }
        //};
        //realm.addChangeListener(realmChangeListener);
    }

    //DISPLAY INPUT DIALOG
    public void displayInputDialog() {

        //EDITTEXTS
        descEditTxt = (EditText) findViewById(R.id.editwrite);
        ImageView fab = (ImageView) findViewById(R.id.send);

        //SAVE
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // descTxt.setVisibility(View.VISIBLE);
                //img.setVisibility(View.GONE);
                String desc = descEditTxt.getText().toString();
                CommonChat s = new CommonChat();
                s.setDescription(desc);
                CommonChatRealmHelper helper = new CommonChatRealmHelper(realm);
                if(helper.save(s)) {
                    descEditTxt.setText("");

                } else {
                    Toast.makeText(CommonChattingAttachmentActivity.this, "Invalid Data", Toast.LENGTH_SHORT).show();
                }
            }


        });
    }

    public void cameraIntent() {
        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        // Intent intent = new Intent(MediaStore.EXTRA_OUTPUT);
        startActivityForResult(intent, REQUEST_CAMERA);
    }

    public void galleryIntent() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);//
        startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
    }

    public void selectImage() {
        final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};
        AlertDialog.Builder builder = new AlertDialog.Builder(CommonChattingAttachmentActivity.this);
        builder.setTitle("Add Photo!");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                boolean result = Utility.checkPermission(CommonChattingAttachmentActivity.this);
                if(items[item].equals("Take Photo")) {
                    userChoosenTask = "Take Photo";
                    if(result) {
                        cameraIntent();
                    }
                } else if(items[item].equals("Choose from Library")) {
                    userChoosenTask = "Choose from Library";
                    if(result) {
                        galleryIntent();
                    }
                } else if(items[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch(requestCode) {
            case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if(userChoosenTask.equals("Take Photo")) {
                        cameraIntent();
                    } else if(userChoosenTask.equals("Choose from Library")) {
                        galleryIntent();
                    }
                } else {
                    //code for deny
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode == Activity.RESULT_OK) {
            if(requestCode == SELECT_FILE) {
                onSelectFromGalleryResult(data);
            } else if(requestCode == REQUEST_CAMERA) {
                onCaptureImageResult(data);
            }

        }
    }

    @SuppressWarnings("deprecation")
    public void onSelectFromGalleryResult(Intent data) {

        Bitmap bm = null;
        if(data != null) {
            try {
                bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
            } catch(IOException e) {
                e.printStackTrace();
            }
        }
        SaveImageVideoData(String.valueOf(bm));
        setAdapters();
    }

    public void onCaptureImageResult(Intent data) {
        Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
        File destination = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
        FileOutputStream fo;
        try {
            destination.createNewFile();
            fo = new FileOutputStream(destination);
            fo.write(bytes.toByteArray());
            fo.close();
        } catch(FileNotFoundException e) {
            e.printStackTrace();
        } catch(IOException e) {
            e.printStackTrace();
        }
        SaveImageVideoData(String.valueOf(destination));
        setAdapters();
    }

    public void SaveImageVideoData(String data) {
        try {
            Realm realm = Realm.getDefaultInstance();
            realm.beginTransaction();
            CommonChat s = realm.createObject(CommonChat.class);
            // obj.setExtensionTypeValue(stringMediaExtType);
            s.setImageUrl(data);
            realm.commitTransaction();
            realm.close();
            setAdapters();
            Log.d("path", data);
            Log.d("working realm", "yes....");
        } catch(Exception ex) {
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        realm.removeChangeListener(realmChangeListener);
        realm.close();
    }
}




public class CommonChattingAttachmentCustomAdapter
        extends BaseAdapter {

    Context c;
    // ArrayList<CommonChat> CommonChats;

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

    // @Override
    // public Object getItem(int position) {
    //     return CommonChats.get(position);
    // }

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




 public class CommonChatRealmHelper {

     Realm realm;
   //  RealmResults<CommonChat> CommonChats;
   //  Boolean saved = null;

     public CommonChatRealmHelper(Realm realm) {
         this.realm = realm;
     }

    // WRITE
     public Boolean save(final CommonChat CommonChat) {
         if(CommonChat == null) {
             saved = false;
         } else {
             realm.executeTransaction(new Realm.Transaction() {
                 @Override
                 public void execute(Realm realm) {

                     try {
                         CommonChat s = realm.copyToRealm(CommonChat);

                         saved = true;

                     } catch(RealmException e) {
                         e.printStackTrace();
                         saved = false;
                     }

                 }
             });
         }


         return saved;
     }

  //   //READ
  //   public void retrieveFromDB() {
  //       CommonChats = realm.where(CommonChat.class).findAll();
  //   }

  //   // REFRESH
  //   public ArrayList<CommonChat> justRefresh() {
  //       ArrayList<CommonChat> latest = new ArrayList<>();
   //      for(CommonChat s : CommonChats) {
  //           latest.add(s);
  //           Log.d("Testing", String.valueOf(s));
  //       }
  //       return latest;
 //    }
  }




你应该做:

public class CommonChattingAttachmentCustomAdapter
        extends RealmBaseAdapter { // from https://github.com/realm/realm-android-adapters
   public CommonChattingAttachmentCustomAdapter(OrderedRealmCollection<ChatCommon> results) {
        super(results);
   }




public void setAdapter() {
    //lv= (ListView) findViewById(R.id.Listview_common);
    //final CommonChatRealmHelper helper = new CommonChatRealmHelper(realm);
    //helper.retrieveFromDB();
    adapter = new CommonChattingAttachmentCustomAdapter(realm.where(CommonChat.class).findAll());
    //adapter = new CommonChattingAttachmentCustomAdapter(this, helper.justRefresh());
    lv.setAdapter(adapter);


查看已注释掉的代码,通常应将其完全删除

10-05 19:02