Я должен опубликовать событие с изображением и некоторыми подписями. Из списка событий я могу редактировать любое событие вместе с изображением. Я использовал библиотеку ('com.theartofdev.edmodo: android-image-cropper: 2.8.0') для обрезки изображения и затем установки его на viewview, но после модернизации я передаю изображение как файл. Что касается редактирования, я передаю переменные с домашней страницы на страницу редактирования. Таким образом, при редактировании, если я не редактировал изображение., При нажатии кнопки сохранения, imageFile становится равным нулю. Как я могу установить imageview как imgFile.
class EditEventActivity : AppCompatActivity() {
private var networkTask: NetworkTask? = null
private var appUtil: AppUtil? = null
private var sessionManager: SessionManager? = null
private var imgFile: File? =null
private var cropImageUri: Uri? = null
var eventid: Int? =null
var regtype:String? =null
private var lottieAnimator:RelativeLayout? =null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_edit_event)
toolbar_title.setText("EDIT EVENT")
setSupportActionBar(custom_toolbar)
supportActionBar?.setDisplayShowTitleEnabled(false)
lottieAnimator=findViewById(R.id.lottieAnimation)
eventid=intent.getIntExtra("eventId",0)
val edtEventName=intent.getStringExtra("eventName")
val edtEventStartDate=intent.getStringExtra("startEvent")
val edtEventEndDate=intent.getStringExtra("endEvent")
val edtDescription=intent.getStringExtra("descript")
val edtImage=intent.getStringExtra("image")
regtype=intent.getStringExtra("regtype")
edit_eventName.setText(edtEventName)
edit_startingEvent.setText(edtEventStartDate)
edit_endingEvent.setText(edtEventEndDate)
edit_description.setText(edtDescription)
Picasso.get().load("http://192.168.0.122:8088/" + edtImage)
.placeholder(com.flat.management.R.drawable.ic_image_placeholder).fit().into(editeventImage)
val c = Calendar.getInstance()
val year = c.get(Calendar.YEAR)
val month = c.get(Calendar.MONTH)
val day = c.get(Calendar.DAY_OF_MONTH)
val mHour = c.get(Calendar.HOUR)
val mMinute = c.get(Calendar.MINUTE)
val mSeconds=c.get(Calendar.SECOND)
edit_startingEvent.setOnClickListener {
val startDate = DatePickerDialog(this, DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
val startTime = TimePickerDialog(this,TimePickerDialog.OnTimeSetListener { view, hh, mm ->
val editTime=String.format("%02d:%02d",hh,mm)
edit_startingEvent.setText("$year-${monthOfYear + 1}-$dayOfMonth " + editTime)
},mHour,mMinute,false).show()
}, year, month, day).show()
}
edit_endingEvent.setOnClickListener {
val endDate=DatePickerDialog(this,DatePickerDialog.OnDateSetListener { datePicker, year, monthOfYear, dayOfMonth ->
val endTime= TimePickerDialog(this, TimePickerDialog.OnTimeSetListener { view, hh, mm ->
val editTime=String.format("%02d:%02d",hh,mm)
edit_endingEvent.setText("$year-${monthOfYear + 1}-$dayOfMonth " + editTime)
},mHour,mMinute,false).show()
},year,month,day).show()
}
editeventImage.setOnClickListener(View.OnClickListener {
CropImage.startPickImageActivity(this)
})
networkTask= NetworkTask(this)
appUtil= AppUtil(this)
sessionManager = SessionManager(this)
edit_eventName!!.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(p0: Editable?) {
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(charSequence: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
})
edit_description!!.addTextChangedListener(object: TextWatcher {
override fun afterTextChanged(p0: Editable?) {
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(charSequence: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
})
btn_editEvent.setOnClickListener(View.OnClickListener {
val mEventName=edit_eventName.text.toString().trim()
val mDescript=edit_description.text.toString().trim()
val mStartDate=edit_startingEvent.text.toString().trim()
val mEndDate=edit_endingEvent.text.toString().trim()
if(TextUtils.isEmpty(mEventName)){
edit_eventName.error="Please enter Event Name"
return@OnClickListener
}
if(TextUtils.isEmpty(mStartDate)){
edit_startingEvent.error="Enter Start Date"
return@OnClickListener
}
if(TextUtils.isEmpty(mEndDate)){
edit_endingEvent.error="Enter End Date"
return@OnClickListener
}
if(TextUtils.isEmpty((mDescript))){
edit_description.error="Please enter description"
return@OnClickListener
}
if(appUtil!!.isNetworkAvailable(this)){
appUtil!!.setScreenNotTouchableFlag()
editEventValues(
imgFile,
eventid!!,
regtype!!,
mEventName,
mStartDate,
mEndDate,
mDescript
)
lottieAnimator?.visibility=View.VISIBLE
}else{
appUtil!!.showErrorToast("Not connected to Internet!!",false)
}
})
}
private fun editEventValues(imgFile: File?, mEventId:Int, mRegtype:String, mEventName: String, mStartDate: String, mEndDate: String, mDescript: String) {
val headerMap: HashMap<String, String> = HashMap<String, String>()
headerMap.put("Authorization", "Bearer " + sessionManager?.getApi_key())
val events=UpdateEventModel()
events.eventname=mEventName
events.startdate=mStartDate
events.enddate=mEndDate
events.regtype=mRegtype
events.description=mDescript
events.eventid=mEventId
val reqFile: RequestBody
val file=File(imgFile!!.path)
reqFile = RequestBody.create(MediaType.parse("image/*"),file)
val part= MultipartBody.Part.createFormData("image", file.name,reqFile)
events.image= part
val eventName= RequestBody.create(MediaType.parse("text/plain"),mEventName)
val startDate= RequestBody.create(MediaType.parse("text/plain"),mStartDate)
val endDate= RequestBody.create(MediaType.parse("text/plain"),mEndDate)
val regType= RequestBody.create(MediaType.parse("text/plain"),mRegtype)
val userId= RequestBody.create(MediaType.parse("text/plain"),mEventId.toString())
val description= RequestBody.create(MediaType.parse("text/plain"),mDescript)
val params = Gson().toJson(events)
Timber.e("Params :"+ params)
val response=networkTask!!.editEventList(headerMap, part, regType, eventName, startDate, endDate, userId, description)
response.enqueue(object: retrofit2.Callback<String> {
override fun onFailure(call: Call<String>, t: Throwable) {
lottieAnimator?.visibility=View.GONE
appUtil!!.clearNotTouchableFlag()
appUtil!!.showErrorToast("Something went Wrong!", false)
Timber.e(t)
}
override fun onResponse(call: Call<String>, response: Response<String>) {
appUtil!!.clearNotTouchableFlag()
lottieAnimator?.visibility=View.GONE
Timber.e("Response : " + response.raw().request().url())
Timber.e("Response : " + response)
Timber.e("Response : " + response.body()!!)
val editevent= Gson().fromJson(response.body(), UpdateEventModel::class.java)
if(editevent.status.equals("true")){
appUtil!!.showToast("Event saved successfully",false)
finish()
}else{
appUtil!!.showErrorToast("Error",false)
}
}
})
}
@SuppressLint("NewApi", "MissingSuperCall")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
// handle result of pick image chooser
if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
val imageUri = CropImage.getPickImageResultUri(this, data)
// For API >= 23 we need to check specifically that we have permissions to read external storage.
if (CropImage.isReadExternalStoragePermissionsRequired(this, imageUri)) {
// request permissions and handle the result in onRequestPermissionsResult()
cropImageUri = imageUri
requestPermissions(arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE), 0)
} else {
// no permissions required or already grunted, can start crop image activity
startCropImageActivity(imageUri)
}
}
// handle result of CropImageActivity
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
val result = CropImage.getActivityResult(data)
if (resultCode == Activity.RESULT_OK) {
val picUri= result.uri
imgFile= File(picUri.path!!)
editeventImage.setImageURI(picUri)
Timber.e("Image Result"+ picUri)
val mFilePath= Environment.getExternalStorageDirectory().toString()
val myDir=File(mFilePath + "/Images")
if(!myDir.exists()){
myDir.mkdirs()
}
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Toast.makeText(this, "Cropping failed: " + result.error, Toast.LENGTH_LONG).show()
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
if (cropImageUri != null && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// required permissions granted, start crop image activity
startCropImageActivity(cropImageUri!!)
} else {
Toast.makeText(this, "Cancelling, required permissions are not granted", Toast.LENGTH_LONG).show()
}
}
/**
* Start crop image activity for the given image.
*/
private fun startCropImageActivity(imageUri: Uri?) {
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(true)
.start(this)
}
}