Android 从其他活动返回后在recyclerview中保留数据

Android 从其他活动返回后在recyclerview中保留数据,android,android-recyclerview,Android,Android Recyclerview,请帮忙,不要投反对票。 我有一个摄像头活动,其中多个图像显示在recyclerview中。单击图像时,会打开一个新的图像预览活动。当我从此图像\u预览返回时,以前单击的所有图像都将丢失 如何恢复这些图像 活动看起来像 RecycleServiceAdapter的代码为: public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> impleme

请帮忙,不要投反对票。 我有一个摄像头活动,其中多个图像显示在
recyclerview
中。单击图像时,会打开一个新的图像预览活动。当我从此
图像\u预览返回时,以前单击的所有图像都将丢失

如何恢复这些图像

活动看起来像

RecycleServiceAdapter
的代码为:

    public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> implements Serializable{

private List<String> horizontalList;
public class MyViewHolder extends RecyclerView.ViewHolder {
    public ImageView image_result;

    public MyViewHolder(View view) {
        super(view);
        image_result = (ImageView) view.findViewById(R.id.image_result);

    }
}


public RecyclerViewAdapter(ArrayList<String> horizontalList) {
    this.horizontalList = horizontalList;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.recyclerview_item_row, parent,false);

    return new MyViewHolder(itemView);

}
@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
   holder.image_result.setImageURI(Uri.parse(horizontalList.get(position)));  // setting image in the recycler view
    holder.image_result.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent=new Intent(v.getContext(),Image_Preview.class);
            intent.putExtra("abc",horizontalList.get(position));
            v.getContext().startActivity(intent);
        }
    });
}


@Override
public int getItemCount() {
    return horizontalList.size();
}

}
在阅读了类似的问题后,我添加了这些方法,但不能完全理解

   protected void onSaveInstanceState(Bundle state) {
    super.onSaveInstanceState(state);

    state.putParcelable("LIST_STATE_KEY", horizontal_lm.onSaveInstanceState());
   // state.putParcelableArrayList("SAVED_RECYCLER_VIEW_DATASET_ID",horizontalList);
}
protected void onRestoreInstanceState(Bundle state) {
    super.onRestoreInstanceState(state);

    listState = state.getParcelable("LIST_STATE_KEY");
    if(state != null)
        listState=state.getParcelable("LIST_STATE_KEY");
}
更新: 我的相机活动

      public class CameraActivity extends AppCompatActivity {
private RecyclerView horizontal_rv;
Bitmap result, upload_bitmap, large_bitmap;
int i=0,j=0;
Calendar c;
Parcelable listState;
String path,large_bitmap_path;
SimpleDateFormat df , tf;
String formattedDate, formattedTime;
String fileName;
ProgressDialog progressDialog;
private ArrayList<String> horizontalList, fileNameList;
ArrayList<Uri> large_bitmapList;
private RecyclerViewAdapter recycleViewAdapter;
CameraView camera;
ImageView back_button;
ImageView switch_camera;
Button upload_btn;
LinearLayoutManager horizontal_lm;
ByteArrayOutputStream bytes;
int flag_camera_switch=0,flag_flash_toggle=0;
ImageView flash_toggle,pick_from_gallery;
private static int LOAD_IMAGE_RESULTS = 1;



@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_camera);
    horizontalList = new ArrayList<>(); // initializing the list for small images
    large_bitmapList=new ArrayList<>();
    fileNameList=new ArrayList<>();
    upload_btn = (Button) findViewById(R.id.upload_icon);  //button to upload image on server

    upload_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
                 uploadButtonClick();
        }});
    camera = (CameraView) findViewById(R.id.camera);
    switch_camera = (ImageView) findViewById(R.id.switch_camera);
    Button button = (Button) findViewById(R.id.capture_button);
    horizontal_rv = (RecyclerView) findViewById(R.id.horizontal_recycler_view);//initializing the recycler view
    horizontal_lm = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); // calling the layout manager
    horizontal_rv.setLayoutManager(horizontal_lm); //setting the layout manager
    recycleViewAdapter = new RecyclerViewAdapter(horizontalList); // initializing the adapter, passing the list
    horizontal_rv.setAdapter(recycleViewAdapter);
    // set up the custom action bar
    horizontal_rv.addOnScrollListener(new RecyclerView.OnScrollListener(){
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState){
            super.onScrollStateChanged(recyclerView, newState);
        }

    });
    camera.setCameraListener(new CameraListener() {
        @Override
        public void onPictureTaken(byte[] picture) {
            super.onPictureTaken(picture);
            upload_bitmap= BitmapFactory.decodeByteArray(picture, 0, picture.length);
            result = BitmapFactory.decodeByteArray(picture, 0, picture.length);
            captureImage();
        }
    });
    //Action Bar
    getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    getSupportActionBar().setDisplayShowCustomEnabled(true);
    getSupportActionBar().setCustomView(R.layout.camera_actionbar);
    View view = getSupportActionBar().getCustomView();
    back_button = (ImageView) view.findViewById(R.id.back_button_actionbar);
    flash_toggle = (ImageView) view.findViewById(R.id.flash_actionbar);
    pick_from_gallery = (ImageView) view.findViewById(R.id.upload_gallery_actionbar);
    pick_from_gallery.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            // Start new activity with the LOAD_IMAGE_RESULTS to handle back the results when image is picked from the Image Gallery.
            startActivityForResult(i, LOAD_IMAGE_RESULTS);
        }
    });
    back_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(CameraActivity.this, DashboardActivty.class);
            startActivity(intent);
            finish();
        }
    });
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try{
                camera.captureImage();
               }
            catch (Exception exception){
                Toast.makeText(getApplicationContext(),"Please wait",Toast.LENGTH_SHORT).show();
            }

        }
    });


    // toggle for camera - front and back
    switch_camera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switchCamera();
        }
    });
    // toggle for flash
    flash_toggle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            flashToggle();
        }
    });
}
public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
    Bitmap resizedBitmap=null;
    try {
        int width = bm.getWidth();
        int height = bm.getHeight();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // CREATE A MATRIX FOR THE MANIPULATION
        Matrix matrix = new Matrix();
        // RESIZE THE BIT MAP
        matrix.postScale(scaleWidth, scaleHeight);

        // "RECREATE" THE NEW BITMAP
        resizedBitmap = Bitmap.createBitmap(
                bm, 0, 0, width, height, matrix, false);
        bm.recycle();
    }
    catch (Exception e){
        Toast.makeText(CameraActivity.this,"Please wait",Toast.LENGTH_SHORT).show();
    }
    return resizedBitmap;
}  // recycle bitmap 50x50
@Override
protected void onResume() {
    super.onResume();
    camera.start();
    if(listState!=null)
        horizontal_lm.onRestoreInstanceState(listState);
}

@Override
protected void onPause() {
    super.onPause();
    camera.stop();

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

    // Here we need to check if the activity that was triggers was the Image Gallery.
    // If it is the requestCode will match the LOAD_IMAGE_RESULTS value.
    // If the resultCode is RESULT_OK and there is some data we know that an image was picked.
    if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK && data != null) {
        // Let's read picked image data - its URI
        Uri pickedImage = data.getData();
        // Let's read picked image path using content resolver
        String[] filePath = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
        cursor.moveToFirst();
        String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
        horizontalList.add(imagePath);
        // At the end remember to close the cursor or you will end with the RuntimeException!
        cursor.close();
    }
} // get image from the gallery
public String getStringImage(Bitmap bmp){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
    return encodedImage;
} // function to get String (Base64) encoded to upload to server
private void uploadImage(final String image_path){
    //Showing the progress dialog
    final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
    StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    //Disimissing the progress dialog
                    loading.dismiss();
                    //Showing toast message of the response
                    Toast.makeText(CameraActivity.this, s , Toast.LENGTH_SHORT).show();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    //Dismissing the progress dialog
                    loading.dismiss();
                    //Showing toast
                    Toast.makeText(CameraActivity.this, "error", Toast.LENGTH_SHORT).show();
                }
            }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
         String img_path=image_path;
            //Converting Bitmap to String

            //Creating parameters
            Map<String,String> parameters = new Hashtable<String, String>();
            //Adding parameters
            parameters.put("postedFile", img_path);
            parameters.put("folderName", "999987");
            parameters.put("categoryName", "Detail Complete");
            parameters.put("estimateNumber", "999999");
            parameters.put("userName", "Chinook/Images");
            parameters.put("imageUploadID", "2017-10-09 01.43.36 PM");
            parameters.put("dateTime", "2017-10-09 01.43 PM");
            parameters.put("type", "image");
            parameters.put("accessToken", "Q)4%v59!@lyr");
            parameters.put("fileName",fileNameList.get(j));
            j++;
            //returning parameters
            return parameters;
        }
    };

    //Creating a Request Queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    //Adding request to the queue
    requestQueue.add(stringRequest);
} // convert image to base64 to upload it. 
public void captureImage(){
            large_bitmap=getResizedBitmap(upload_bitmap,500);
            bytes = new ByteArrayOutputStream();
            result.compress(Bitmap.CompressFormat.JPEG, 25, bytes);
            Bitmap newResult=getResizedBitmap(result,400,400);
            String fileNameSmall = new SimpleDateFormat("yyyyMMddHHmmss'.txt'").format(new Date());
            String fileNameLarge= new SimpleDateFormat("HHmmss'.txt'").format(new Date());
            path = MediaStore.Images.Media.insertImage(getApplicationContext().getContentResolver(), newResult, fileNameSmall, null);
            large_bitmap_path= MediaStore.Images.Media.insertImage(getApplicationContext().getContentResolver(), large_bitmap, fileNameLarge, null);
            c = Calendar.getInstance();
            df = new SimpleDateFormat("yyyy-MM-dd");
            fileNameList.add(fileName);
            horizontalList.add(path);
            large_bitmapList.add(Uri.parse(large_bitmap_path));
            i++;
            recycleViewAdapter.notifyDataSetChanged();
}
public SSLContext getSslContext() {

    TrustManager[] byPassTrustManagers = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) {
        }
    } };

    SSLContext sslContext=null;

    try {
        sslContext = SSLContext.getInstance("TLS");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    try {
        sslContext.init(null, byPassTrustManagers, new SecureRandom());
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    return sslContext;

}
public void flashToggle(){
    if(flag_flash_toggle==0){
        camera.setFlash(CameraKit.Constants.FLASH_AUTO);
        flash_toggle.setImageResource(R.drawable.camera_flash_auto);
        flag_flash_toggle=1;
    }
    else if(flag_flash_toggle==1){
        camera.setFlash(CameraKit.Constants.FLASH_ON);
        flag_flash_toggle=2;
        flash_toggle.setImageResource(R.drawable.camera_flash_on);
    }
    else if(flag_flash_toggle==2){
        camera.setFlash(CameraKit.Constants.FLASH_OFF);
        flash_toggle.setImageResource(R.drawable.camera_flash_off);
        flag_flash_toggle=0;
    }


} // function to toggle the camera
public void switchCamera(){
    if(flag_camera_switch==0){
        camera.setFacing(CameraKit.Constants.FACING_BACK);
        flag_camera_switch=1;
    }
    else if(flag_camera_switch==1){
        camera.setFacing(CameraKit.Constants.FACING_FRONT);
        flag_camera_switch=0;
    }
} // function to switch between front and back camera
public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
    int width = image.getWidth();
    int height = image.getHeight();

    float bitmapRatio = (float)width / (float) height;
    if (bitmapRatio > 1) {
        width = maxSize;
        height = (int) (width / bitmapRatio);
    } else {
        height = maxSize;
        width = (int) (height * bitmapRatio);
    }
    return Bitmap.createScaledBitmap(image, width, height, true);
} // resize image for uploading ; overloaded function
public void uploadButtonClick(){
    getSslContext();
    for (int i=0;i<large_bitmapList.size();i++)
        //uploadImage(getStringImage(large_bitmap));
        try {
            uploadImage(getStringImage(MediaStore.Images.Media.getBitmap(this.getContentResolver(), large_bitmapList.get(i))));
        } catch (IOException e) {
          Toast.makeText(CameraActivity.this,"Erro..",Toast.LENGTH_SHORT).show();
        }

} // code to upload images on the server
protected void onSaveInstanceState(Bundle state) {
    super.onSaveInstanceState(state);

    state.putParcelable("LIST_STATE_KEY", horizontal_lm.onSaveInstanceState());
  // state.putParcelableArrayList("SAVED_RECYCLER_VIEW_DATASET_ID",horizontalList);
}
protected void onRestoreInstanceState(Bundle state) {
    super.onRestoreInstanceState(state);

    listState = state.getParcelable("LIST_STATE_KEY");
    if(state != null)
        listState=state.getParcelable("LIST_STATE_KEY");
}
公共类CameraActivity扩展了AppCompatActivity{
私人回收站视图水平_rv;
位图结果,上传\u位图,大\u位图;
int i=0,j=0;
日历c;
可包裹列表状态;
字符串路径,大位图路径;
简化格式df,tf;
字符串formattedDate,formattedTime;
字符串文件名;
进行对话进行对话;
私有ArrayList水平列表,文件名列表;
ArrayList大\位映射列表;
私人回收设施;
摄像机;
图像查看后退按钮;
图像视图开关\摄像机;
按钮上传;
直线布局经理水平;
ByteArrayOutputStream字节;
int flag_camera_switch=0,flag_flash_toggle=0;
ImageView flash_切换,从_图库中选择_;
私有静态整型加载\图像\结果=1;
@凌驾
创建时受保护的void(@Nullable Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_摄像头);
horizontalist=new ArrayList();//初始化小图像的列表
大的位图列表=新的ArrayList();
fileNameList=newarraylist();
upload_btn=(按钮)findViewById(R.id.upload_图标);//在服务器上上载图像的按钮
upload_btn.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
上传按钮单击();
}});
摄像头=(CameraView)findViewById(R.id.camera);
开关\摄像机=(图像视图)findViewById(R.id.开关\摄像机);
按钮按钮=(按钮)findViewById(R.id.capture_按钮);
horizontal_rv=(RecyclerView)findViewById(R.id.horizontal_recycler_视图);//初始化recycler视图
horizontal_lm=新建LinearLayoutManager(this,LinearLayoutManager.horizontal,false);//调用布局管理器
水平设置布局管理器(水平设置);//设置布局管理器
recycleViewAdapter=new RecycleServiceAdapter(horizontalList);//初始化适配器,传递列表
水平安装适配器(循环水适配器);
//设置自定义操作栏
horizontal_rv.addOnScrollListener(新的RecyclerView.OnScrollListener(){
@凌驾
CrollStateChanged上的公共无效(RecyclerView RecyclerView,int newState){
super.onScrollStateChanged(recyclerView、newState);
}
});
camera.setCameraListener(新的CameraListener(){
@凌驾
公共无效onPictureTaken(字节[]图片){
super.onPictureTaken(图片);
upload_bitmap=BitmapFactory.decodeByteArray(图片,0,图片.长度);
结果=位图工厂.decodeByteArray(图片,0,图片.长度);
captureImage();
}
});
//动作条
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY\u SHOW\u CUSTOM);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setCustomView(R.layout.camera\u actionbar);
视图=getSupportActionBar().getCustomView();
后退按钮=(ImageView)view.findViewById(R.id.back按钮动作栏);
flash\u toggle=(ImageView)view.findviewbyd(R.id.flash\u actionbar);
从_gallery=(ImageView)view.findViewById(R.id.upload_gallery_actionbar)中选择_;
从_gallery.setOnClickListener(新视图.OnClickListener()中选择_){
@凌驾
公共void onClick(视图){
Intent i=新Intent(Intent.ACTION\u PICK,android.provider.MediaStore.Images.Media.EXTERNAL\u CONTENT\u URI);
//使用LOAD_IMAGE_结果启动新活动,以便在从图像库中拾取图像时返回结果。
startActivityForResult(i,加载图像结果);
}
});
后退按钮.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
意向意向=新意向(CameraActivity.this、DashboardActivty.class);
星触觉(意向);
完成();
}
});
setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
试一试{
camera.captureImage();
}
捕获(异常){
Toast.makeText(getApplicationContext(),“请稍候”,Toast.LENGTH\u SHORT.show();
}
}
});
//相机切换-前后
切换\u camera.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
开关摄像机();
}
});
//闪光开关
flash_toggle.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
flashToggle();
}
});
}
公共位图getResizedBitmap(位图bm、int-newWidth、int-newHeight){
位图resizedBitmap=null;
试一试{
int width=bm.getWidth();
int height=bm.getHeight();
浮动比例宽度=((浮动)新宽度)/宽度;
浮动刻度高度=((浮动)新高度)/高度;
//为操纵创建一个矩阵
矩阵=新矩阵();
//调整位图的大小
矩阵。后标度(标度宽度、标度高度);
//“重新创建”新位图
resizedBitmap=Bitmap.createBitmap(
bm,0,0,宽度,高度,矩阵,假);
bm.recycle();
}
捕获(例外e){
Toast.makeText(
      public class CameraActivity extends AppCompatActivity {
private RecyclerView horizontal_rv;
Bitmap result, upload_bitmap, large_bitmap;
int i=0,j=0;
Calendar c;
Parcelable listState;
String path,large_bitmap_path;
SimpleDateFormat df , tf;
String formattedDate, formattedTime;
String fileName;
ProgressDialog progressDialog;
private ArrayList<String> horizontalList, fileNameList;
ArrayList<Uri> large_bitmapList;
private RecyclerViewAdapter recycleViewAdapter;
CameraView camera;
ImageView back_button;
ImageView switch_camera;
Button upload_btn;
LinearLayoutManager horizontal_lm;
ByteArrayOutputStream bytes;
int flag_camera_switch=0,flag_flash_toggle=0;
ImageView flash_toggle,pick_from_gallery;
private static int LOAD_IMAGE_RESULTS = 1;



@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_camera);
    horizontalList = new ArrayList<>(); // initializing the list for small images
    large_bitmapList=new ArrayList<>();
    fileNameList=new ArrayList<>();
    upload_btn = (Button) findViewById(R.id.upload_icon);  //button to upload image on server

    upload_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
                 uploadButtonClick();
        }});
    camera = (CameraView) findViewById(R.id.camera);
    switch_camera = (ImageView) findViewById(R.id.switch_camera);
    Button button = (Button) findViewById(R.id.capture_button);
    horizontal_rv = (RecyclerView) findViewById(R.id.horizontal_recycler_view);//initializing the recycler view
    horizontal_lm = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); // calling the layout manager
    horizontal_rv.setLayoutManager(horizontal_lm); //setting the layout manager
    recycleViewAdapter = new RecyclerViewAdapter(horizontalList); // initializing the adapter, passing the list
    horizontal_rv.setAdapter(recycleViewAdapter);
    // set up the custom action bar
    horizontal_rv.addOnScrollListener(new RecyclerView.OnScrollListener(){
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState){
            super.onScrollStateChanged(recyclerView, newState);
        }

    });
    camera.setCameraListener(new CameraListener() {
        @Override
        public void onPictureTaken(byte[] picture) {
            super.onPictureTaken(picture);
            upload_bitmap= BitmapFactory.decodeByteArray(picture, 0, picture.length);
            result = BitmapFactory.decodeByteArray(picture, 0, picture.length);
            captureImage();
        }
    });
    //Action Bar
    getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    getSupportActionBar().setDisplayShowCustomEnabled(true);
    getSupportActionBar().setCustomView(R.layout.camera_actionbar);
    View view = getSupportActionBar().getCustomView();
    back_button = (ImageView) view.findViewById(R.id.back_button_actionbar);
    flash_toggle = (ImageView) view.findViewById(R.id.flash_actionbar);
    pick_from_gallery = (ImageView) view.findViewById(R.id.upload_gallery_actionbar);
    pick_from_gallery.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            // Start new activity with the LOAD_IMAGE_RESULTS to handle back the results when image is picked from the Image Gallery.
            startActivityForResult(i, LOAD_IMAGE_RESULTS);
        }
    });
    back_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(CameraActivity.this, DashboardActivty.class);
            startActivity(intent);
            finish();
        }
    });
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try{
                camera.captureImage();
               }
            catch (Exception exception){
                Toast.makeText(getApplicationContext(),"Please wait",Toast.LENGTH_SHORT).show();
            }

        }
    });


    // toggle for camera - front and back
    switch_camera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switchCamera();
        }
    });
    // toggle for flash
    flash_toggle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            flashToggle();
        }
    });
}
public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
    Bitmap resizedBitmap=null;
    try {
        int width = bm.getWidth();
        int height = bm.getHeight();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // CREATE A MATRIX FOR THE MANIPULATION
        Matrix matrix = new Matrix();
        // RESIZE THE BIT MAP
        matrix.postScale(scaleWidth, scaleHeight);

        // "RECREATE" THE NEW BITMAP
        resizedBitmap = Bitmap.createBitmap(
                bm, 0, 0, width, height, matrix, false);
        bm.recycle();
    }
    catch (Exception e){
        Toast.makeText(CameraActivity.this,"Please wait",Toast.LENGTH_SHORT).show();
    }
    return resizedBitmap;
}  // recycle bitmap 50x50
@Override
protected void onResume() {
    super.onResume();
    camera.start();
    if(listState!=null)
        horizontal_lm.onRestoreInstanceState(listState);
}

@Override
protected void onPause() {
    super.onPause();
    camera.stop();

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

    // Here we need to check if the activity that was triggers was the Image Gallery.
    // If it is the requestCode will match the LOAD_IMAGE_RESULTS value.
    // If the resultCode is RESULT_OK and there is some data we know that an image was picked.
    if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK && data != null) {
        // Let's read picked image data - its URI
        Uri pickedImage = data.getData();
        // Let's read picked image path using content resolver
        String[] filePath = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
        cursor.moveToFirst();
        String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
        horizontalList.add(imagePath);
        // At the end remember to close the cursor or you will end with the RuntimeException!
        cursor.close();
    }
} // get image from the gallery
public String getStringImage(Bitmap bmp){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
    return encodedImage;
} // function to get String (Base64) encoded to upload to server
private void uploadImage(final String image_path){
    //Showing the progress dialog
    final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
    StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    //Disimissing the progress dialog
                    loading.dismiss();
                    //Showing toast message of the response
                    Toast.makeText(CameraActivity.this, s , Toast.LENGTH_SHORT).show();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    //Dismissing the progress dialog
                    loading.dismiss();
                    //Showing toast
                    Toast.makeText(CameraActivity.this, "error", Toast.LENGTH_SHORT).show();
                }
            }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
         String img_path=image_path;
            //Converting Bitmap to String

            //Creating parameters
            Map<String,String> parameters = new Hashtable<String, String>();
            //Adding parameters
            parameters.put("postedFile", img_path);
            parameters.put("folderName", "999987");
            parameters.put("categoryName", "Detail Complete");
            parameters.put("estimateNumber", "999999");
            parameters.put("userName", "Chinook/Images");
            parameters.put("imageUploadID", "2017-10-09 01.43.36 PM");
            parameters.put("dateTime", "2017-10-09 01.43 PM");
            parameters.put("type", "image");
            parameters.put("accessToken", "Q)4%v59!@lyr");
            parameters.put("fileName",fileNameList.get(j));
            j++;
            //returning parameters
            return parameters;
        }
    };

    //Creating a Request Queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    //Adding request to the queue
    requestQueue.add(stringRequest);
} // convert image to base64 to upload it. 
public void captureImage(){
            large_bitmap=getResizedBitmap(upload_bitmap,500);
            bytes = new ByteArrayOutputStream();
            result.compress(Bitmap.CompressFormat.JPEG, 25, bytes);
            Bitmap newResult=getResizedBitmap(result,400,400);
            String fileNameSmall = new SimpleDateFormat("yyyyMMddHHmmss'.txt'").format(new Date());
            String fileNameLarge= new SimpleDateFormat("HHmmss'.txt'").format(new Date());
            path = MediaStore.Images.Media.insertImage(getApplicationContext().getContentResolver(), newResult, fileNameSmall, null);
            large_bitmap_path= MediaStore.Images.Media.insertImage(getApplicationContext().getContentResolver(), large_bitmap, fileNameLarge, null);
            c = Calendar.getInstance();
            df = new SimpleDateFormat("yyyy-MM-dd");
            fileNameList.add(fileName);
            horizontalList.add(path);
            large_bitmapList.add(Uri.parse(large_bitmap_path));
            i++;
            recycleViewAdapter.notifyDataSetChanged();
}
public SSLContext getSslContext() {

    TrustManager[] byPassTrustManagers = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) {
        }
    } };

    SSLContext sslContext=null;

    try {
        sslContext = SSLContext.getInstance("TLS");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    try {
        sslContext.init(null, byPassTrustManagers, new SecureRandom());
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    return sslContext;

}
public void flashToggle(){
    if(flag_flash_toggle==0){
        camera.setFlash(CameraKit.Constants.FLASH_AUTO);
        flash_toggle.setImageResource(R.drawable.camera_flash_auto);
        flag_flash_toggle=1;
    }
    else if(flag_flash_toggle==1){
        camera.setFlash(CameraKit.Constants.FLASH_ON);
        flag_flash_toggle=2;
        flash_toggle.setImageResource(R.drawable.camera_flash_on);
    }
    else if(flag_flash_toggle==2){
        camera.setFlash(CameraKit.Constants.FLASH_OFF);
        flash_toggle.setImageResource(R.drawable.camera_flash_off);
        flag_flash_toggle=0;
    }


} // function to toggle the camera
public void switchCamera(){
    if(flag_camera_switch==0){
        camera.setFacing(CameraKit.Constants.FACING_BACK);
        flag_camera_switch=1;
    }
    else if(flag_camera_switch==1){
        camera.setFacing(CameraKit.Constants.FACING_FRONT);
        flag_camera_switch=0;
    }
} // function to switch between front and back camera
public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
    int width = image.getWidth();
    int height = image.getHeight();

    float bitmapRatio = (float)width / (float) height;
    if (bitmapRatio > 1) {
        width = maxSize;
        height = (int) (width / bitmapRatio);
    } else {
        height = maxSize;
        width = (int) (height * bitmapRatio);
    }
    return Bitmap.createScaledBitmap(image, width, height, true);
} // resize image for uploading ; overloaded function
public void uploadButtonClick(){
    getSslContext();
    for (int i=0;i<large_bitmapList.size();i++)
        //uploadImage(getStringImage(large_bitmap));
        try {
            uploadImage(getStringImage(MediaStore.Images.Media.getBitmap(this.getContentResolver(), large_bitmapList.get(i))));
        } catch (IOException e) {
          Toast.makeText(CameraActivity.this,"Erro..",Toast.LENGTH_SHORT).show();
        }

} // code to upload images on the server
protected void onSaveInstanceState(Bundle state) {
    super.onSaveInstanceState(state);

    state.putParcelable("LIST_STATE_KEY", horizontal_lm.onSaveInstanceState());
  // state.putParcelableArrayList("SAVED_RECYCLER_VIEW_DATASET_ID",horizontalList);
}
protected void onRestoreInstanceState(Bundle state) {
    super.onRestoreInstanceState(state);

    listState = state.getParcelable("LIST_STATE_KEY");
    if(state != null)
        listState=state.getParcelable("LIST_STATE_KEY");
}
@Override   
public void onSaveInstanceState(Bundle savedState) {
 savedState.putStringArrayList("LIST_STATE_KEY", horizontalList);
 super.onSaveInstanceState(savedState);
}

@Override
public void onCreate (Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 horizontalList = new ArrayList();
 if (savedInstanceState != null) {
  ArrayList<String> list = savedInstanceState.getStringArrayList("LIST_STATE_KEY");
  if (list != null) {
     horizontalList = list;
    }
  }
}
@Override 
public boolean onSupportNavigateUp() { 
 finish(); 
 return true; 
}