Java tutorial
package net.jongrakko.zipsuri.activity; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.location.LocationManager; import android.media.ThumbnailUtils; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.TextView; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.wdullaer.materialdatetimepicker.date.DatePickerDialog; import com.yalantis.ucrop.UCrop; import net.jongrakko.zipsuri.R; import net.jongrakko.zipsuri.manager.ProgressManger; import net.jongrakko.zipsuri.manager.ServerManager; import net.jongrakko.zipsuri.model.AddressModel; import net.jongrakko.zipsuri.model.PostModel; import net.jongrakko.zipsuri.view.CheckableButton; import net.jongrakko.zipsuri.view.simpleimagedownloadview.SimpleImageDownloadView; import net.jongrakko.zipsuri.view.simpleimagedownloadview.thread.ImageDownloadThread; import java.io.File; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; /** * Created by MoonJongRak on 2016. 5. 11.. */ public class PostReviseActivity extends Fragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener, OnMapReadyCallback, OnMyLocationButtonClickListener, GoogleMap.OnMapClickListener { private static final int PICK_PHOTO_FOR_AVATAR = 100; private static final int TAKE_PHOTO_FOR_AVATAR = 104; private static final int TAKE_VIDEO_FOR_AVATAR = 105; private static final int PICK_VIDEO_FOR_AVATAR = 103; private static final int SEARCH_ADDRESS = 101; private static final int MY_LOCATION_REQUEST_CODE = 102; private int[] licenseButtonIds = { R.id.buttonLicense0, R.id.buttonLicense1, R.id.buttonLicense2, R.id.buttonLicense3, R.id.buttonLicense4, R.id.buttonLicense5, R.id.buttonLicense6, R.id.buttonLicense7, R.id.buttonLicense8, R.id.buttonLicense9, R.id.buttonLicense10, R.id.buttonLicense11, R.id.buttonLicense12, R.id.buttonLicense13, R.id.buttonLicense14, R.id.buttonLicense15 }; private int[] postImageViewIds = { R.id.imageView_0, R.id.imageView_1, R.id.imageView_2, R.id.imageView_3, R.id.imageView_4, }; private int[] postImageViewPlusIds = { R.id.imageView_plus_0, R.id.imageView_plus_1, R.id.imageView_plus_2, R.id.imageView_plus_3, R.id.imageView_plus_4, }; private int[] postImageViewRemoveIds = { R.id.imageView_remove_0, R.id.imageView_remove_1, R.id.imageView_remove_2, R.id.imageView_remove_3, R.id.imageView_remove_4, }; private ImageView mImageViewTitle; private EditText mEditTextContent, mEditTextAddress; private TextView mTextViewDate, mTextViewTime; private GoogleMap mGoogleMap; private PostModel uploadPostModel; private PostModel mRevisePostModel; private AddressModel reviseAddressModel; private long uploadEndDate; private View rootView; private int alreadyExistsImages = 0; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.activity_revise_post, container, false); setLayout(); return rootView; } public void setData(PostModel revisePostModel) { this.mRevisePostModel = revisePostModel; } private void setLayout() { // reviseAddressModel = mRevisePostModel.getAddressModel(); mImageViewTitle = (ImageView) rootView.findViewById(R.id.imageViewTitle); // mEditTextContent = (EditText) rootView.findViewById(R.id.editTextContent); mEditTextContent.setText(mRevisePostModel.getContent()); mEditTextAddress = (EditText) rootView.findViewById(R.id.editTextAddress); mEditTextAddress.setText(mRevisePostModel.getAddress()); uploadEndDate = mRevisePostModel.getEndDate(); mTextViewDate = (TextView) rootView.findViewById(R.id.textViewDate); mTextViewDate.setText(new SimpleDateFormat("yyyy-MM-dd").format(mRevisePostModel.getEndDate())); mTextViewTime = (TextView) rootView.findViewById(R.id.textViewTime); mTextViewTime.setText(new SimpleDateFormat("HH:mm").format(mRevisePostModel.getEndDate())); rootView.findViewById(R.id.imageViewVideo).setOnClickListener(this); ((RadioButton) rootView.findViewById(R.id.radioButtonAddressGPS)).setOnCheckedChangeListener(this); ((RadioButton) rootView.findViewById(R.id.radioButtonAddressSelf)).setOnCheckedChangeListener(this); setLicense(); rootView.findViewById(R.id.imageViewLeft).setOnClickListener(this); rootView.findViewById(R.id.imageViewRight).setOnClickListener(this); rootView.findViewById(R.id.buttonDone).setOnClickListener(this); rootView.findViewById(R.id.layoutDateMain).setOnClickListener(this); rootView.findViewById(R.id.imageView_remove_video).setOnClickListener(this); for (int id : postImageViewIds) { rootView.findViewById(id).setOnClickListener(this); } for (int id : postImageViewPlusIds) { rootView.findViewById(id).setOnClickListener(this); } for (int id : postImageViewRemoveIds) { rootView.findViewById(id).setOnClickListener(this); } initImageView(); SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager() .findFragmentById(R.id.googleMap); mapFragment.getMapAsync(this); } private void setLicense() { for (int i = 0; i < PostModel.FLAG_LICENSE.length; i++) { if ((mRevisePostModel.getLicense() & PostModel.FLAG_LICENSE[i]) != 0) { ((CheckableButton) rootView.findViewById(licenseButtonIds[i])).setChecked(true); } else { ((CheckableButton) rootView.findViewById(licenseButtonIds[i])).setChecked(false); } rootView.findViewById(licenseButtonIds[i]).setClickable(false); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.imageViewLeft: titlePictureLeft(); break; case R.id.imageViewRight: titlePictureRight(); break; case R.id.layoutDateMain: showSetTimePicker(); break; case R.id.editTextAddress: startActivityForResult(new Intent(getContext(), SearchAddressActivity.class), SEARCH_ADDRESS); break; case R.id.buttonDone: uploadPost(); break; case R.id.imageViewVideo: showVideoDialog(); break; case R.id.imageView_remove_video: removeVideo(); break; default: for (int id : postImageViewIds) { if (v.getId() == id) { Object tag = rootView.findViewById(id).getTag(); if (tag != null) { startActivityPhoto(tag.toString()); } else { showPhotoDialog(); } return; } } for (int i = 0; i < postImageViewPlusIds.length; i++) { if (v.getId() == postImageViewPlusIds[i]) { rootView.findViewById(postImageViewIds[i]).callOnClick(); return; } } for (int i = 0; i < postImageViewPlusIds.length; i++) { if (v.getId() == postImageViewRemoveIds[i]) { removeImage(i); return; } } break; } } private void startActivityPhoto(String path) { Intent intent = new Intent(getContext(), PhotoActivity.class); intent.putExtra(PhotoActivity.INTENT_FILE, path); startActivity(intent); } private void showPhotoDialog() { if (rootView.findViewById(postImageViewIds[postImageViewIds.length - 1]).getTag() != null) { ProgressManger.showToast("? 5 ."); return; } new AlertDialog.Builder(getContext()).setTitle("?") .setItems(new String[] { " ?", "" }, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: takeImage(); break; case 1: pickImage(); break; } } }).show(); } private void showVideoDialog() { new AlertDialog.Builder(getContext()).setTitle("?") .setItems(new String[] { "??? ?", "" }, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: takeVideo(); break; case 1: pickVideo(); break; } } }).show(); } private void showSetTimePicker() { final Calendar now = Calendar.getInstance(); final Calendar time = Calendar.getInstance(); DatePickerDialog mDatePickerDialog = DatePickerDialog.newInstance(new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) { time.set(year, monthOfYear, dayOfMonth, 18, 0); uploadEndDate = time.getTimeInMillis(); mTextViewDate.setText(new SimpleDateFormat("yyyy-MM-dd").format(time.getTime())); mTextViewTime.setText(new SimpleDateFormat("HH:mm").format(time.getTime())); } }, now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH)); mDatePickerDialog.setAccentColor(getResources().getColor(R.color.calendarAccent)); mDatePickerDialog.show(getActivity().getFragmentManager(), ""); } private void titlePictureRight() { Object tag = mImageViewTitle.getTag(); if (tag == null) { return; } for (int i = 0; i < postImageViewIds.length - 1; i++) { int id = postImageViewIds[i + 1]; if (rootView.findViewById(id).getTag() == null) { return; } if (tag.equals(postImageViewIds[i])) { mImageViewTitle.setImageDrawable(((ImageView) rootView.findViewById(id)).getDrawable()); mImageViewTitle.setTag(id); break; } } } private void titlePictureLeft() { Object tag = mImageViewTitle.getTag(); if (tag == null) { return; } for (int i = 1; i < postImageViewIds.length; i++) { int id = postImageViewIds[i - 1]; if (rootView.findViewById(id).getTag() == null) { return; } if (tag.equals(postImageViewIds[i])) { mImageViewTitle.setImageDrawable(((ImageView) rootView.findViewById(id)).getDrawable()); mImageViewTitle.setTag(id); break; } } } private long getLicense() { long result = 0; for (int i = 0; i < licenseButtonIds.length; i++) { if (((CheckableButton) rootView.findViewById(licenseButtonIds[i])).isChecked()) { result |= PostModel.FLAG_LICENSE[i]; } } return result; } private void uploadPost() { if (mEditTextContent.getText().toString().equals("")) { ProgressManger.showToast("? ."); return; } else if (getLicense() == 0) { ProgressManger.showToast("1 ??? ? ."); return; } else if (reviseAddressModel == null) { ProgressManger.showToast(" ."); return; } else if (uploadEndDate == 0) { ProgressManger.showToast("?? ."); return; } uploadPostModel = new PostModel(); uploadPostModel.setPostId(mRevisePostModel.getPostId()); uploadPostModel.setContent(mEditTextContent.getText().toString()); uploadPostModel.setLicense(getLicense()); uploadPostModel.setAddressModel(reviseAddressModel); uploadPostModel.setEndDate(uploadEndDate); ServerManager.revisePost(new ServerManager.OnServerListener<Void>(getContext()) { @Override protected void onSuccess(Void data) { ProgressManger.showToast(" !"); getActivity().onBackPressed(); } }, uploadPostModel); } //<--Start of Pick Image private void initImageView() { List<String> paths = mRevisePostModel.getImagePathUrl(); /* mImageViewTitle = (ImageView) rootView.findViewById(R.id.imageViewTitle); mImageViewTitle.setOnClickListener(this); rootView.findViewById(R.id.imageViewRight).setOnClickListener(this); rootView.findViewById(R.id.imageViewLeft).setOnClickListener(this); */ for (int i = 0; i < postImageViewIds.length; i++) { try { final String imageUrl = paths.get(i); Log.e("IMAGE" + i, paths.get(i)); SimpleImageDownloadView imageView = (SimpleImageDownloadView) rootView .findViewById(postImageViewIds[i]); imageView.setOnClickListener(this); imageView.setImageURL(imageUrl, 4); imageView.setPadding(10, 10, 10, 10); imageView.setScaleType(ImageView.ScaleType.FIT_XY); } catch (Exception e) { } } } private void pickImage() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/*"); startActivityForResult(intent, PICK_PHOTO_FOR_AVATAR); } private void pickVideo() { Intent intent = new Intent(Intent.ACTION_PICK); intent.setType(MediaStore.Video.Media.CONTENT_TYPE); intent.setData(MediaStore.Video.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent, PICK_VIDEO_FOR_AVATAR); } File takeFile; private void takeImage() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); takeFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Zisuri_tmp_" + System.currentTimeMillis() + ".jpg"); Uri saveUri = Uri.fromFile(takeFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, saveUri); // set the image file name startActivityForResult(intent, TAKE_PHOTO_FOR_AVATAR); } private void takeVideo() { Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); takeFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Zisuri_tmp_" + System.currentTimeMillis() + ".mp4"); Uri saveUri = Uri.fromFile(takeFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, saveUri); // set the image file name intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // set the video image quality to high startActivityForResult(intent, TAKE_VIDEO_FOR_AVATAR); } private void removeImage(int index) { for (int i = index; i < postImageViewIds.length - 1; i++) { int nextIndex = i + 1; ImageView nowImage = (ImageView) rootView.findViewById(postImageViewIds[i]); ImageView nextImage = (ImageView) rootView.findViewById(postImageViewIds[nextIndex]); nowImage.setImageDrawable(nextImage.getDrawable()); nowImage.setTag(nextImage.getTag()); rootView.findViewById(postImageViewPlusIds[i]) .setVisibility(rootView.findViewById(postImageViewPlusIds[nextIndex]).getVisibility()); rootView.findViewById(postImageViewRemoveIds[i]) .setVisibility(rootView.findViewById(postImageViewRemoveIds[nextIndex]).getVisibility()); if (nowImage.getTag() == null) { nowImage.setScaleType(ImageView.ScaleType.CENTER_INSIDE); } else { nowImage.setScaleType(ImageView.ScaleType.FIT_XY); } } int lastIndex = postImageViewIds.length - 1; ImageView lastImage = (ImageView) rootView.findViewById(postImageViewIds[lastIndex]); lastImage.setImageResource(R.drawable.ic_add_photo); lastImage.setScaleType(ImageView.ScaleType.CENTER_INSIDE); lastImage.setTag(null); rootView.findViewById(postImageViewPlusIds[lastIndex]).setVisibility(View.GONE); rootView.findViewById(postImageViewRemoveIds[lastIndex]).setVisibility(View.GONE); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK && requestCode == UCrop.REQUEST_CROP) { File cropFile = new File(UCrop.getOutput(data).getPath()); int index = 0; for (int id : postImageViewIds) { ImageView mImageView = (ImageView) rootView.findViewById(id); if (mImageView.getTag() == null) { rootView.findViewById(postImageViewPlusIds[index]).setVisibility(View.VISIBLE); rootView.findViewById(postImageViewRemoveIds[index]).setVisibility(View.VISIBLE); mImageView.setImageBitmap(BitmapFactory.decodeFile(cropFile.getPath())); mImageView.setScaleType(ImageView.ScaleType.FIT_XY); mImageView.setPadding(10, 10, 10, 10); mImageView.setTag(cropFile.getPath()); mImageViewTitle.setImageDrawable(((ImageView) rootView.findViewById(id)).getDrawable()); mImageViewTitle.setTag(id); break; } index++; } } else if (resultCode == Activity.RESULT_OK && requestCode == PICK_PHOTO_FOR_AVATAR) { UCrop.of(data.getData(), Uri.fromFile( new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), System.currentTimeMillis() + ".jpg"))) .withMaxResultSize(1920, 1920).start(getContext(), this); } else if (resultCode == Activity.RESULT_OK && requestCode == TAKE_PHOTO_FOR_AVATAR) { UCrop.of(Uri.fromFile(takeFile), Uri.fromFile( new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), System.currentTimeMillis() + ".jpg"))) .withMaxResultSize(1920, 1920).start(getContext(), this); } else if (resultCode == UCrop.RESULT_ERROR) { final Throwable cropError = UCrop.getError(data); Log.d("mox", "croperror" + cropError.toString()); } else if (resultCode == Activity.RESULT_OK && requestCode == SEARCH_ADDRESS) { AddressModel mAddressModel = (AddressModel) data.getSerializableExtra("data"); setAddressModel(mAddressModel); } else if (resultCode == Activity.RESULT_OK && requestCode == PICK_VIDEO_FOR_AVATAR) { String path = getPath(data.getData()); showVideoAlertDialog(path); } else if (resultCode == Activity.RESULT_OK && requestCode == TAKE_VIDEO_FOR_AVATAR) { String path = takeFile.getPath(); showVideoAlertDialog(path); } } private void showVideoAlertDialog(final String path) { double size = ((double) new File(path).length()) / (1024 * 1024); size = Math.round(size * 100) / 100.0; new AlertDialog.Builder(getContext()).setMessage("?").setMessage( "??? ? ?? .\n? Wifi .\n( " + size + "MB )") .setNegativeButton("", null) .setPositiveButton("?", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Bitmap thumb = ThumbnailUtils.createVideoThumbnail(path, MediaStore.Video.Thumbnails.MINI_KIND); ((ImageView) rootView.findViewById(R.id.imageViewVideo)).setImageBitmap(thumb); ((ImageView) rootView.findViewById(R.id.imageViewVideo)) .setScaleType(ImageView.ScaleType.FIT_XY); uploadPostModel.setVideo(path); rootView.findViewById(R.id.imageView_remove_video).setVisibility(View.VISIBLE); } }).show(); } private void removeVideo() { ((ImageView) rootView.findViewById(R.id.imageViewVideo)).setImageResource(R.drawable.ic_add_video); ((ImageView) rootView.findViewById(R.id.imageViewVideo)).setScaleType(ImageView.ScaleType.CENTER_INSIDE); uploadPostModel.setVideo(null); rootView.findViewById(R.id.imageView_remove_video).setVisibility(View.GONE); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { switch (buttonView.getId()) { case R.id.radioButtonAddressGPS: mEditTextAddress.setOnClickListener(null); this.mGoogleMap.setOnMapClickListener(this); this.mGoogleMap.setOnMyLocationButtonClickListener(this); if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mGoogleMap.setMyLocationEnabled(true); } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, MY_LOCATION_REQUEST_CODE); } } break; case R.id.radioButtonAddressSelf: this.mGoogleMap.setOnMapClickListener(null); mEditTextAddress.setOnClickListener(this); this.mGoogleMap.setOnMyLocationButtonClickListener(null); mGoogleMap.setMyLocationEnabled(false); mEditTextAddress.setOnClickListener(this); startActivityForResult(new Intent(getContext(), SearchAddressActivity.class), SEARCH_ADDRESS); break; } } } @Override public void onMapReady(GoogleMap googleMap) { this.mGoogleMap = googleMap; this.mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(37.541, 126.986), 18)); this.mGoogleMap.setOnMapClickListener(null); } private void setAddressModel(AddressModel addressModel) { LatLng mLocation = new LatLng(addressModel.getLatitude(), addressModel.getLongitude()); this.reviseAddressModel = addressModel; mEditTextAddress.setText(addressModel.getRoadAddr()); MarkerOptions markerOptions = new MarkerOptions(); markerOptions.position(mLocation); mGoogleMap.addMarker(markerOptions); mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mLocation, 18)); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == MY_LOCATION_REQUEST_CODE) { if (permissions.length == 1 && permissions[0].equals(Manifest.permission.ACCESS_FINE_LOCATION) && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } mGoogleMap.setMyLocationEnabled(true); } else { ProgressManger.showToast("? ."); } } } @Override public boolean onMyLocationButtonClick() { LocationManager mLocationManager = (LocationManager) getActivity() .getSystemService(Context.LOCATION_SERVICE); if (!mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { ProgressManger.showToast(" ."); } else { ProgressManger.showToast(" ..."); } return false; } @Override public void onMapClick(LatLng latLng) { mGoogleMap.clear(); AddressModel mAddressModelTmp = new AddressModel(); mAddressModelTmp.setLatitude(latLng.latitude); mAddressModelTmp.setLongitude(latLng.longitude); ServerManager.reverseGeoCoding(new ServerManager.OnServerListener<AddressModel>(getContext()) { @Override protected void onSuccess(AddressModel data) { setAddressModel(data); } }, mAddressModelTmp); } // private String getPath(Uri uri) { String[] projection = { MediaStore.Video.Media.DATA }; Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } }