Fragment中的listview更新item中的Imageview

项目中需要实现保存图片到数据库,再次进入更新控件

  • 展示图片到控件上
  • 保存图片路径
  • 设置全局变量,再次进入时根据全局变量来判断是否展示保存的图片路径

调取摄像头

 Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//打开相机的Intent
        if (takePhotoIntent!= null) {

           //创建用来保存照片的文件
            File imageFile = autoImageUtil.createImageFile();

            if (imageFile != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    /*7.0以上要通过FileProvider将File转化为Uri*/
                    mImageUri = FileProvider.getUriForFile(mActivity, FILE_PROVIDER_AUTHORITY, imageFile);
                } else {
                    /*7.0以下则直接使用Uri的fromFile方法将File转化为Uri*/
                    mImageUri = Uri.fromFile(imageFile);
                }
                //将用于输出的文件Uri传递给相机
                takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
                //打开相机
                startActivityForResult(takePhotoIntent, TAKE_PHOTO);
            }
        }

创建图片保存路径

public File createImageFile() {
      String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        File imageFile = null;
        try {
            imageFile = File.createTempFile(imageFileName, ".jpg", storageDir);
        } catch (Exception e) {
            e.printStackTrace(); 
        }
        return imageFile;
    }
  • 在onActivityResult中判断是否拍摄成功,将图片保存到的imageUri,通过BitmapFractory生成Bitmap,将Bitmap保存到ImageBean对象中
	if (resultCode == Activity.RESULT_OK) {
	     isSavedImage = false;
	     try {
	        imageBeans.clear();
	        ImageBean imageBean = new ImageBean();
	
	       /*如果拍照成功,将Uri用BitmapFactory的decodeStream方法转为Bitmap*/
	       Bitmap bitmap = BitmapFactory.decodeStream(mActivity.getContentResolver().openInputStream(mImageUri));
	
	       int bitmapDegree = CamerUtils.getBitmapDegree(mImageUri.getPath());
	       Log.e(TAG, "onActivityResult: 图片角度==" + bitmapDegree + mImageUri + bitmap);
	       Bitmap newBitmap = autoImageUtil.AddTimeWatermark(bitmap);
	       imageBean.setBitmap(newBitmap);
	       //保存水印图片
	       Map<String, String> stringStringMap = autoImageUtil.SaveImagFile(newBitmap);
	      
	      imageBean.setBitmapPath(AutoImageUtil.getFilePathByUri(mActivity, mImageUri));
	      imageBean.ImagePath = stringStringMap;
	//    imageBean.setBitmapPath(AutoImageUtil.Uri2Path(mActivity,mImageUri));
	      imageBeans.add(imageBean);
	
	      //如果imageBean集合size发生变化 则通知quploadAdapter更新
	       qUploadAdapter.notifyDataSetChanged();
	       } catch (Exception e) {
	        e.printStackTrace();
	         Log.e(TAG, "onActivityResult: " + e.toString());
	          }
	     }
  • AutoImageUtil类

public class AutoImageUtil {
    private Context context;
    public AutoImageUtil(Context context) {
        this.context = context;
    }
    /**
     * 添加时间水印
     *
     * @param mBitmap
     * @return mNewBitmap
     */
    public Bitmap AddTimeWatermark(Bitmap mBitmap) {

        return AddTimeWatermark(mBitmap, null);
    }

    public Bitmap AddTimeWatermark(Bitmap mBitmap, String time) {

        //获取原始图片与水印图片的宽与高
        int mBitmapWidth = mBitmap.getWidth();
        int mBitmapHeight = mBitmap.getHeight();
        Bitmap mNewBitmap = Bitmap.createBitmap(mBitmapWidth, mBitmapHeight, Bitmap.Config.ARGB_8888);
        Canvas mCanvas = new Canvas(mNewBitmap);

        //向位图中开始画入MBitmap原始图片
        mCanvas.drawBitmap(mBitmap, 0, 0, null);
        //添加文字
        Paint mPaint = new Paint();
        String mFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss EEEE").format(new Date());
        Location bestLocation = LocationUtil.getBestLocation(context, null);
        String gpsAddress = GPSUtil.GetAddressStr(bestLocation, context);

        String mFormat2 = gpsAddress;
        mPaint.setColor(Color.RED);
        mPaint.setAntiAlias(true);
        mPaint.setTextSize(100);
        //水印的位置坐标
        mCanvas.drawText(mFormat, (mBitmapWidth * 1) / 10, (mBitmapHeight * 13) / 15, mPaint);
        mCanvas.drawText(mFormat2, (mBitmapWidth * 1) / 10, (mBitmapHeight * 14) / 15, mPaint);
//        if (FreshItemFragment.time != null){
////
////            mCanvas.drawText(FreshItemFragment.time+"", (mBitmapWidth * 1) / 10,(mBitmapHeight*2)/15,mPaint);
////        }
//        mCanvas.save(Canvas.ALL_SAVE_FLAG);
        mCanvas.save();
        mCanvas.restore();

        return mNewBitmap;

    }

    public Map<String,String> SaveImagFile(Bitmap bitmap) {
        Map<String,String> bitmapPath = new HashMap<>();
        File appDir = new File(Environment.getExternalStorageDirectory(), "ctr");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        // 保存的文件名
        String fileName = System.currentTimeMillis() + ".jpeg";

        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        bitmapPath.put(appDir.getAbsolutePath(),fileName);
        return bitmapPath;
    }


    public static Bitmap getBitmapFromLocal(String filePath, String fileName) {
        try {
            File file = new File(filePath, fileName);
            if (file.exists()) {
                Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(file));
                Log.e(TAG, "getBitmapFromLocal: "+ bitmap );
                return bitmap;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "getBitmapFromLocal: "+ e.toString() );
        }
        return null;
    }


    /**
     * 创建用来存储图片的文件,以时间来命名就不会产生命名冲突
     *
     * @return 创建的图片文件
     */
    public File createImageFile() {
        @SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        File imageFile = null;
        try {
            imageFile = File.createTempFile(imageFileName, ".jpg", storageDir);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "createImageFile: " + e.toString() + "01010101010101");
        }
        return imageFile;

    }


    /**
     * Try to return the absolute file path from the given Uri
     *
     * @param context
     * @param uri
     * @return the file path or null
     */
    public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null) data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }


    public static String Uri2Path(Context context, Uri uri) {
//        String[] projection = {MediaStore.Video.Media.DATA};
        String[] projection = {MediaStore.Images.Media.DATA};
        ContentResolver cr = context.getContentResolver();
        Cursor cursor = cr.query(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }


    public static String getFilePathByUri(Context context, Uri uri) {
        String path = null;
        // 以 file:// 开头的
        if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
            path = uri.getPath();
            return path;
        }
        // 以 content:// 开头的,比如 content://media/extenral/images/media/17766
        if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme()) && Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.Media.DATA}, null, null, null);
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    if (columnIndex > -1) {
                        path = cursor.getString(columnIndex);
                    }
                }
                cursor.close();
            }
            return path;
        }
        // 4.4及之后的 是以 content:// 开头的,比如 content://com.android.providers.media.documents/document/image%3A235700
        if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme()) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (DocumentsContract.isDocumentUri(context, uri)) {
                if (isExternalStorageDocument(uri)) {
                    // ExternalStorageProvider
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];
                    if ("primary".equalsIgnoreCase(type)) {
                        path = Environment.getExternalStorageDirectory() + "/" + split[1];
                        return path;
                    }
                } else if (isDownloadsDocument(uri)) {
                    // DownloadsProvider
                    final String id = DocumentsContract.getDocumentId(uri);
                    final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                    path = getDataColumn(context, contentUri, null, null);
                    return path;
                } else if (isMediaDocument(uri)) {
                    // MediaProvider
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];
                    Uri contentUri = null;
                    if ("image".equals(type)) {
                        contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    } else if ("video".equals(type)) {
                        contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    } else if ("audio".equals(type)) {
                        contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                    }
                    final String selection = "_id=?";
                    final String[] selectionArgs = new String[]{split[1]};
                    path = getDataColumn(context, contentUri, selection, selectionArgs);
                    return path;
                }
            }
        }
        return null;
    }

    private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null) cursor.close();
        }
        return null;
    }

    private static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    private static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    private static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }


}

  • ResultTable 其中静态工具类MyStringUtil中的变量AP** 是数据库名

public class ResultTable {

    private static final String TAG = "ResultTable";
    private static BlankAnswerResult result;
    private  Context context;

    /**
     * Instantiates a new Result table.
     *
     * @param context the context
     */
    public ResultTable(Context context) {
        this.context = context;
    }

    /**
     * Save result.
     *
     * @param resultBean the result bean
     * @param context    the context
     */
    public static void saveResult(ResultBean resultBean, Context context){

        ContentValues contentValues = new ContentValues();
        contentValues.put("ID",resultBean.ID);
        contentValues.put("DeliveryID",resultBean.DeliveryID);
        contentValues.put("QuestionnaireID",resultBean.QuestionnaireID);
        contentValues.put("ClientID",resultBean.ClientID);
        contentValues.put("ProjectID",resultBean.ProjectID);
        contentValues.put("CurrentQuestionID",resultBean.CurrentQuestionID);
        contentValues.put("VisitUserID",resultBean.VisitUserID);
        contentValues.put("VisitBeginTime",resultBean.VisitBeginTime.getTime());
        contentValues.put("VisitEndTime",resultBean.VisitEndTime.getTime());
        contentValues.put("FromDate",resultBean.FromDate.getTime());
        contentValues.put("ToDate",resultBean.ToDate.getTime());
        contentValues.put("Score",resultBean.Score);
        contentValues.put("Description",resultBean.Description);
        contentValues.put("CurrentProgress",resultBean.CurrentProgress);
        contentValues.put("UploadBeginTime",resultBean.UploadBeginTime.getTime());
        contentValues.put("UploadEndTime",resultBean.UploadEndTime.getTime());
        contentValues.put("Status",resultBean.Status);
        contentValues.put("Address",resultBean.Address);
        contentValues.put("LocationX",resultBean.LocationX);
        contentValues.put("LocationY",resultBean.LocationY);

        MyDataBasesHelper myDataBasesHelper = MyDataBasesHelper.getInstance(context);

        myDataBasesHelper.insert(contentValues, MyStringUtil.APQuestionnaireResults);

    }

    /**
     * Get result id string.
     *
     * @param deliveryID the delivery id
     * @param context    the context
     * @return the string
     */
    public static String getResultID(int deliveryID, Context context){
        String resultID = "";
        MyDataBasesHelper myDataBasesHelper = MyDataBasesHelper.getInstance(context);

        String [] columns = {"ID"};
        String selection = "DeliveryID=?";
        String [] selectionArgs = {String.valueOf(deliveryID)};
        Cursor cursor = myDataBasesHelper.query(MyStringUtil.APQuestionnaireResults, columns,selection,selectionArgs);
        if (cursor.moveToFirst() == false)
        {
            cursor.close();
            return resultID;
        }
        resultID = cursor.getString(cursor.getColumnIndex("ID"));
        cursor.close();
        return resultID;
    }

    /**
     * Save answer.
     *
     * @param answersBean the answers bean
     * @param isUpdate    the is update
     * @param context     the context
     */
    public static void saveAnswer(AnswersBean answersBean, boolean isUpdate,Context context) {

        ContentValues contentValues = new ContentValues();
        contentValues.put("ResultID", answersBean.ResultID);
        contentValues.put("QuestionID", answersBean.QuestionID);
        contentValues.put("Description", answersBean.Description);
        contentValues.put("Status", answersBean.Status);
        contentValues.put("TotalScore", answersBean.TotalScore);
        MyDataBasesHelper myDataBasesHelper = MyDataBasesHelper.getInstance(context);
        if (isUpdate) {
            contentValues.put("LastModifiedTime", answersBean.LastModifiedTime.getTime());
            contentValues.put("LastModifiedUserID", answersBean.LastModifiedUserID);

            String[] whereArgs = {answersBean.ID};
            myDataBasesHelper.update(contentValues, "ID=?", whereArgs, MyStringUtil.APAnswers);
        } else {
            contentValues.put("ID", answersBean.ID);
            contentValues.put("CreateTime", answersBean.CreateTime.getTime());
            contentValues.put("CreateUserID", answersBean.CreateUserID);

            myDataBasesHelper.insert(contentValues, MyStringUtil.APAnswers);
        }
    }

    /**
     * Gets answer id.
     *
     * @param questionID the question id
     * @param resultID   the result id
     * @param context    the context
     * @return the answer id
     */
    public static String getAnswerID(int questionID, String resultID, Context context) {
        String answerID = "";
        MyDataBasesHelper myDataBasesHelper = MyDataBasesHelper.getInstance(context);

        String[] columns = {"ID"};
        String selection = "QuestionID=? and ResultID=?";
        String[] selectionArgs = {String.valueOf(questionID), resultID};
        Cursor cursor = myDataBasesHelper.query(MyStringUtil.APAnswers, columns, selection, selectionArgs);
        if (cursor.moveToNext()) {
            answerID = cursor.getString(cursor.getColumnIndex("ID"));

            Log.e(TAG, "getAnswerID() returned: " + answerID);
        }
        cursor.close();
        return answerID;
    }

    /**
     * Save answer option.
     *
     * @param answersOptionBean the answers option bean
     * @param context           the context
     */
    public static void saveAnswerOption(AnswersOptionBean answersOptionBean, Context context) {

        ContentValues contentValues = new ContentValues();
        contentValues.put("ID", answersOptionBean.ID);
        contentValues.put("AnswerID", answersOptionBean.AnswerID);
        contentValues.put("OptionID", answersOptionBean.OptionID);
        contentValues.put("OptionText", answersOptionBean.OptionText);

        Log.e(TAG, "saveAnswerOption: " +  answersOptionBean.OptionText);
        MyDataBasesHelper myDataBasesHelper = MyDataBasesHelper.getInstance(context);

        myDataBasesHelper.insert(contentValues, APAnswerOptions);
    }

    /**
     * Delete answer options by answer id.
     *
     * @param answerID the answer id
     * @param context  the context
     */
    public static void deleteAnswerOptionsByAnswerID(String answerID, Context context) {

        MyDataBasesHelper myDataBasesHelper = MyDataBasesHelper.getInstance(context);
        String selection = "answerID=?";
        String[] selectionArgs = {answerID};
        myDataBasesHelper.delete(selection, selectionArgs, APAnswerOptions);

    }

    /**
     * 首次答题保存完结果 未提交 当再次进去问卷时 将结果从数据库中取出来赋值给当前题目
     * 用当前的questionID去查 answerResult 表 获取当前所答题目获得的总分 totalScore
     * questionID 查 answerOptions表 获取当前选项的所选的内容 将保存的值赋值给当前题目的选项结果
     *
     * @param questionID the question id
     * @param resultID   the result id
     * @param context    the context
     * @return the saved answer
     */


    public static BlankAnswerResult getSavedAnswer(int questionID, String resultID, Context context) {
        List<BlankAnswerResult> results = new ArrayList<>();
        double totalScore = 0.0;
        String answerID = " ";
        MyDataBasesHelper myDataBasesHelper = MyDataBasesHelper.getInstance(context);

        String[] columns = {"TotalScore", "ID"};
        String selection = "ResultID=? and QuestionID=?";
        String[] selectionArgs = {resultID,String.valueOf(questionID)};
        Cursor cursor = myDataBasesHelper.query(MyStringUtil.APAnswers, columns, selection, selectionArgs);

        if (cursor.moveToNext()){
            totalScore = cursor.getDouble(cursor.getColumnIndex("TotalScore"));
            answerID = cursor.getString(cursor.getColumnIndex("ID"));
        }
        cursor.close();

        String[] optionColumns = {"OptionText","OptionID"};
        String optionSelection = "AnswerID=?";
        String[] optionSelectionArgs = {answerID};
        Log.e(TAG, "getSavedAnswer: " + answerID );

        Cursor optionCursor = myDataBasesHelper.query(MyStringUtil.APAnswerOptions, optionColumns, optionSelection, optionSelectionArgs);

        String optionText = "";
        int optionID = -1;

        if (optionCursor.moveToNext()){
            optionID = optionCursor.getInt(optionCursor.getColumnIndex("OptionID"));
            optionText = optionCursor.getString(optionCursor.getColumnIndex("OptionText"));

//            results.add(result);
            Log.e(TAG, "getSavedAnswer: " + optionText);
        }
        result = new BlankAnswerResult();
        result.AnswerID = answerID;
        result.TotalScore = totalScore;
        result.OptionText = optionText;
        result.OptionID = optionID;
        optionCursor.close();

        return result;
    }


    //多选题读库操作

    /**
     * Gets mulit answer.
     *
     * @param questionID the question id
     * @param resultID   the result id
     * @param context    the context
     * @return the mulit answer
     */
    public static List<MulitAnswerResult> getMulitAnswer(int questionID, String resultID, Context context) {
        List<MulitAnswerResult> results = new ArrayList<>();
        double totalScore = 0.0;
        String answerID = " ";
        MyDataBasesHelper myDataBasesHelper = MyDataBasesHelper.getInstance(context);

        String[] columns = {"TotalScore", "ID"};
        String selection = "ResultID=? and QuestionID=?";
        String[] selectionArgs = {resultID,String.valueOf(questionID)};
        Cursor cursor = myDataBasesHelper.query(MyStringUtil.APAnswers, columns, selection, selectionArgs);

        if (cursor.moveToNext()){
            totalScore = cursor.getDouble(cursor.getColumnIndex("TotalScore"));
            answerID = cursor.getString(cursor.getColumnIndex("ID"));
        }
        cursor.close();

        String[] optionColumns = {"OptionText","OptionID"};
        String optionSelection = "AnswerID=?";
        String[] optionSelectionArgs = {answerID};
        Log.e(TAG, "getSavedAnswer: " + answerID );

        Cursor optionCursor = myDataBasesHelper.query(MyStringUtil.APAnswerOptions, optionColumns, optionSelection, optionSelectionArgs);

        String optionText = "";
        int optionID = -1;
        results.clear();
        if (optionCursor != null){
            while (optionCursor.moveToNext()){
                MulitAnswerResult  mulitResult = new MulitAnswerResult();
                optionID = optionCursor.getInt(optionCursor.getColumnIndex("OptionID"));
                optionText = optionCursor.getString(optionCursor.getColumnIndex("OptionText"));

                mulitResult.OptionText = optionText;
                mulitResult.OptionID = optionID;
                results.add(mulitResult);
                Log.e(TAG, "getSavedAnswer: " + optionID);
            }

        }
        optionCursor.close();

        return results;
    }

    /**
     * Gets option id.
     *
     * @param QuestionID the question id
     * @param Title      the title
     * @param context    the context
     * @return the option id
     */
    public static List<Integer> getOptionId(int QuestionID,String Title,Context context) {
        int questionID = -1;
        List<Integer> optionIDList = new ArrayList<>();
        MyDataBasesHelper myDataBasesHelper = MyDataBasesHelper.getInstance(context);
        String[] optionColumns = {"ID"};
        String optionSelection = "QuestionID=? and Title =?";
        String[] optionSelectionArgs = {String.valueOf(QuestionID), Title};
        Cursor query = myDataBasesHelper.query(MyStringUtil.APOptions, optionColumns, optionSelection, optionSelectionArgs);
        if (query.moveToNext()) {
             questionID = query.getInt(query.getColumnIndex("ID"));
            optionIDList.add(questionID);
        }
        query.close();
        return optionIDList;
    }

    /**
     * Save answers string.
     *
     * @param questionBean the question bean
     * @param resultID     the result id
     * @param context      the context
     * @return the string
     */
//保存填空题到本地库
    public static String SaveAnswers(QuestionBean questionBean,String resultID,Context context) {

        int questionID = questionBean.getID();
        double totalScore = questionBean.TotalScore;
        String answerID = ResultTable.getAnswerID(questionID, resultID, context);
        boolean isUpdate = !answerID.equals("");
        if (answerID.equals("")) {
            answerID = UUID.randomUUID().toString();
        }
//            Log.e(TAG, "SaveBlankAnswers : " + answerID);
        AnswersBean answersBean = new AnswersBean();
        answersBean.ID = answerID;
        answersBean.ResultID = resultID;
        answersBean.CreateTime = new Date();
        answersBean.CreateUserID = MyStringUtil.userIDTemp;
        answersBean.LastModifiedTime = new Date();
        answersBean.LastModifiedUserID = MyStringUtil.userIDTemp;
        answersBean.QuestionID = questionID;
        answersBean.Status = 1;
        answersBean.TotalScore = totalScore;

        ResultTable.saveAnswer(answersBean, isUpdate, context);


        return answerID;

    }
    /**
     * Save single options.
     *
     * @param questionType   the question type
     * @param answerID       the answer id
     * @param optionID       the option id
     * @param additionalText the additional text
     */
    public void SaveSingleOptions(int questionType, String answerID, int optionID, String additionalText) {

        Map<Integer, String> answerOptionList = new HashMap<Integer, String>();
        answerOptionList.put(optionID, additionalText);
        SaveMutilpleOptions(questionType, answerID, answerOptionList);
    }

    /**
     * Save mulite options.
     *
     * @param questionType   the question type
     * @param answerID       the answer id
     * @param optionIDs      the option i ds
     * @param additionalText the additional text
     */
    public void SaveMuliteOptions(int questionType, String answerID, List<Integer> optionIDs, String additionalText) {

        Map<Integer, String> answerOptionList = new HashMap<Integer, String>();
        for (Integer optionID: optionIDs){

            answerOptionList.put(optionID, additionalText);
        }
        SaveMutilpleOptions(questionType, answerID, answerOptionList);
    }


    public  void  SaveImages(int questionType,String answerID ,List<String> imageUrl ){

        Map<Integer, String> indexImageUrl = new HashMap<>();
        for (String path : imageUrl){
            int index = imageUrl.indexOf(path);
            indexImageUrl.put(index,path);
        }

        SaveMutilpleOptions(questionType,answerID,indexImageUrl);
    }


    /**
     * Save mutilple options.
     *
     * @param questionType     the question type
     * @param answerID         the answer id
     * @param answerOptionList the answer option list
     */
    public  void SaveMutilpleOptions(int questionType, String answerID, Map<Integer, String> answerOptionList) {


        ResultTable.deleteAnswerOptionsByAnswerID(answerID, context);
        
        Set<Integer> optionIDList = answerOptionList.keySet();
        
        for (Integer key : optionIDList) {
            int optionID = key;
            String additionalText = answerOptionList.get(key);
            String answerOptionID = UUID.randomUUID().toString();
            AnswersOptionBean optionBean = new AnswersOptionBean();
            optionBean.ID = answerOptionID;
            optionBean.AnswerID = answerID;
            optionBean.OptionID = optionID;
            optionBean.OptionText = additionalText;

            ResultTable.saveAnswerOption(optionBean, context);
        }
    }



}

  • 点击下一题保存当前结果
 			isSavedImage = true;

                // 多媒体的逻辑 takephoto  中 保存照片路径地址 createimageUrl  照相返回结果 onActivityResult  phtoto  video audio
                //将返回结果 保存在对应的bean对象中,怎么在listview中 保存 连接地址 然后再默认加载的时候读取数据库显示出来
                List<String> pathList = new ArrayList<>();
                pathList.clear();
                //图片
                for (int i = 0; i < imageBeans.size(); i++) {
                    //
                    ImageBean imageBean = imageBeans.get(i);
                    String fileName = imageBean.ImagePath.get(Constants.FilePath);
                    Log.e(TAG, "SaveCurrentQuestionAnswers: " + fileName);
                    pathList.add(fileName);
                }
                //只存图片路径
                resultTable.SaveImages(8, answerID, pathList);
  • 然后就是listview的Adapter中的逻辑了
  • 其中Constants.FilePath是一个常量 图片保存的路径,"/storage/emulated/0/ctr"
 //显示保存的图片数据 查询数据库
        //全局变量isSaveImage
        if (isSavedImage) {
            imgBitmaps.clear();
            List<MulitAnswerResult> mulitAnswer = ResultTable.getMulitAnswer(questionBean.getID(), resultID, context);
            if (mulitAnswer != null && mulitAnswer.size() != 0) {
                //有保存的图片数据 循环取出 保存的图片名称

                for (MulitAnswerResult result : mulitAnswer) {
                    String fileName = result.getOptionText();
                    //根据图片路径 和名称 生成bitmap
                    Bitmap bitmapFromLocal = AutoImageUtil.getBitmapFromLocal(Constants.FilePath, fileName);
                    imgBitmaps.add(bitmapFromLocal);
                    Log.e(TAG, "getView: imgBitmaps= " + imgBitmaps.size() +"fileName="+fileName+" bitmapFromLocal = "+ bitmapFromLocal);
                }

            }
        }
            if (imageBeans.size() != 0) {
                // 加载图片布局
                imgBitmaps.clear();
                for (ImageBean bean : imageBeans) {
                    imgBitmaps.add(bean.getBitmap());
                  
                }

            }
            //查看大图
        itemClick(viewHolder.gv,imgBitmaps);

        //如何改变
        imageAdapter imageAdapter = new imageAdapter(imgBitmaps);
        viewHolder.gv.setAdapter(imageAdapter);
        imageAdapter.notifyDataSetChanged();

  • itemClick item点击显示大图
private void itemClick(NoScrollGridView view, final List<Bitmap> imageBeans){
        view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final Dialog dialog = new Dialog(context, R.style.AppTheme_FullScreenDialog);
                //imagebeans是fragment的全局变量 每次加载时imagebeans不被清空 所以相同题型都会共用
                ImageView imgShowview = new ImageView(context);
                //之前逻辑 将imagebean对象的集合传进来 adapter的count和item都基于imagbeans来加载   现在将拍摄的图片名称和路径保存到数据库 首次加载判断,没有保存的数据就不予显示 image_upload_view
                waterbitmap = imageBeans.get(position);
                WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
                lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                lp.height = WindowManager.LayoutParams.MATCH_PARENT;
                dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
                dialog.setContentView(imgShowview);
                dialog.getWindow().setAttributes(lp);
                imgShowview.setImageBitmap(waterbitmap);
                dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                dialog.setCancelable(true);
                dialog.show();
                imgShowview.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
            }
        });
    }
  • fragment中的listview中有三中布局 因为需要适配其他布局所以依旧使用fragment中的listview作为容器,返回itemcount = 1;
  • listview中的子view中的ImageAdapter代码如下,在Fragment中维护一个list 集合,所以每次都需要清空,否则其他布局会显示相同图片。后期还要再做优化
  • 通过方法 Bitmap bitmapFromLocal = AutoImageUtil.getBitmapFromLocal(Constants.FilePath, fileName);
    imgBitmaps.add(bitmapFromLocal);
    传入到imageAdapter中
/**
     * The type Image adapter.
     */
    /**
     * 图片适配器
     */
    public class imageAdapter extends BaseAdapter {

        private List<Bitmap> saveImagePath;
        private ImageView imageView;
        //加载图片布局时
        public imageAdapter(List<Bitmap> imagePahts) {
            saveImagePath = imagePahts;
        }



        @Override
        public int getCount() {
//            if (saveImagePath.size() != 0){
//                return saveImagePath.size();
//            }
//            return imageBeans.size();
            return 1;
        }

        @Override
        public Object getItem(int position) {

            return imageBeans.get(position);
        }

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

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            ImageView image = new ImageView(context);
            image.setLayoutParams(new LinearLayout.LayoutParams(400,600));

            if (saveImagePath.size()!=0){

                for(int i =0 ;i < saveImagePath.size();i++){

                    waterbitmap = saveImagePath.get(i);
//                    imageView = itemImgs.get(i);
                }
            }
            if (imageBeans.size() !=0){
                for (ImageBean imageBean: imageBeans){

                    waterbitmap = imageBean.getBitmap();
                }
            }

            BitmapDrawable bitmapDrawable = new BitmapDrawable(context.getResources(), waterbitmap);

           image.setImageDrawable(bitmapDrawable);

            tempImage = image;

            return image;
        }

        class imageViewHolder{
            ImageView image;
        }

    }
  • 先写到这里吧
  • 后期需要将图片压缩上传到服务器
    加油!!!

你可能感兴趣的:(android)