Pic The High Quailty Images Send to The Server
java Activity code
package com.example.reBLISS.view
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.AsyncTask
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.FileProvider
import com.example.reBLISS.BuildConfig
import com.example.reBLISS.R
import com.example.reBLISS.modal.Mymodal
import com.example.reBLISS.retrofit.ApiClient
import com.example.reBLISS.retrofit.ApiInterface
import com.kaopiz.kprogresshud.KProgressHUD
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody.Part.Companion.createFormData
import okhttp3.RequestBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
class ActivityCamara : AppCompatActivity() {
val value:Int=20
private var kProgressHUD: KProgressHUD? = null
private val ADHAR_IMAGE_CLICK_REQUEST = 205
private var mImageUri: Uri? = null
lateinit var camara:Button
lateinit var imges:ImageView
private lateinit var mCurrentPhotoPath: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_camara)
imges=findViewById(R.id.imges1)
camara=findViewById(R.id.camra)
camara.setOnClickListener{
if (isStoragePermissionGranted())
{
dispatchTakePictureIntentReal(ADHAR_IMAGE_CLICK_REQUEST)
}
else{
}
}
}
inner class CreateFile(var type: Int) : AsyncTask<String, File, File>() {
override fun doInBackground(vararg strings: String): File? {
var file: File? = null
try {
val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
val imageFileName = "JPEG_" + timeStamp + "_"
val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
file = File.createTempFile(
imageFileName, // prefix /
".jpg", // suffix /
storageDir // directory /
)
} catch (e: IOException) {
e.printStackTrace()
}
// Save a file: path for use with ACTION_VIEW intents
return file
}
override fun onPostExecute(file: File?) {
super.onPostExecute(file)
if (file != null) {
mCurrentPhotoPath = file.absolutePath
callCamera(file, type)
}
}
}
private fun callCamera(file: File?, type: Int) {
if (file != null) {
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(packageManager) != null) {
// Continue only if the File was successfully created*/
if (file != null) {
val photoURI = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileprovider", file)
mImageUri = Uri.fromFile(file)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
startActivityForResult(takePictureIntent, type)
}
}
}
}
private fun dispatchTakePictureIntentReal(panImageClickRequest: Int) {
CreateFile(panImageClickRequest).execute()
}
private fun callImagePost(imagePath: Uri?, imagePathReal: String) {
try {
kProgressHUD = KProgressHUD.create(this)
.setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
.setCancellable(false)
.setAnimationSpeed(2)
.setDimAmount(0.5f)
.show()
} catch (e: java.lang.Exception) {
e.printStackTrace()
}
var imageFile: File
if (imagePath != null) {
imageFile = File(com.example.reBLISS.util.Utils.getRealPathFromUri(this, imagePath))
}
else {
imageFile = File(imagePathReal)
}
val requestFile = RequestBody.create("image/*".toMediaTypeOrNull(), imageFile)
val apiInterface: ApiInterface = ApiClient.getClient().create(ApiInterface::class.java)
val call: Call<Mymodal> = apiInterface.uploadNewsFeedImages(createFormData("file", imageFile.name, requestFile),"rwerwe", 44)
call.enqueue(object : Callback<Mymodal?> {
override fun onResponse(call: Call<Mymodal?>, response: Response<Mymodal?>) {
// btnSubmit.revertAnimation()
try {
// ApiModel addMediaModel = response.body();
// if(addMediaModel.getStatusCode().equals("200")){
Toast.makeText(applicationContext, "Files uploaded successfuly", Toast.LENGTH_SHORT
).show()
kProgressHUD?.dismiss()
// }
// Log.e("main", "the message is ----> " + addMediaModel.getStatusMessage());
} catch (e: Exception) {
Log.d("Exception", "|=>" + e.message)
//
Toast.makeText(
applicationContext,
"Faild images",
Toast.LENGTH_SHORT
).show()
kProgressHUD?.dismiss()
}
}
override fun onFailure(call: Call<Mymodal?>, t: Throwable) {
// btnSubmit.revertAnimation()
kProgressHUD?.dismiss()
Log.i("my", t.message!!)
}
})
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
callImagePost(null, mCurrentPhotoPath!!)
}
fun isStoragePermissionGranted(): Boolean {
return if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED) {
Log.v("permission", "Permission is granted")
true
} else {
Log.v("permission", "Permission is revoked")
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA), 1)
false
}
} else {
//permission is automatically granted on sdk<23 upon installation
Log.v("permission", "Permission is granted")
true
}
}
}
xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:background="@color/white"
android:layout_height="match_parent"
tools:context=".view.ActivityCamara">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/imges1"
android:layout_gravity="center"
android:src="@drawable/ic_launcher_background"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/camra"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello camra!"
android:layout_marginTop="43dp"
android:layout_gravity="center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.4"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.298" />
</LinearLayout>
ApiInterface
@Multipart
@POST("checkin")
Call<Mymodal> uploadNewsFeedImages(@Part MultipartBody.Part files ,@Part("location") String location,@Part("uid")long uid );
manifest
Permission
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature
android:name="android.hardware.camera"
android:required="true" />
Dependency:
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.9.0'
ContentProvider:
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.gps.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/files_paths"></meta-data>
</provider>
Xml Folder
//// every application change the paths name
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-files-path name="my_images" path="/" />
</paths>
Util class
package com.example.reBLISS.util;
import android.content.Context;
import android.database.Cursor;
import android.location.Address;
import android.location.Geocoder;
import android.net.Uri;
import android.provider.MediaStore;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Utils {
public static final String GSTINFORMAT_REGEX = "[0-9]{2}[a-zA-Z]{5}[0-9]{4}[a-zA-Z]{1}[1-9A-Za-z]{1}[Z]{1}[0-9a-zA-Z]{1}";
public static final String GSTN_CODEPOINT_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static String addressR = "", cityR = "", stateR = "",districtR ="";
public static String getRealPathFromUri(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public static String getPincode(Context context, double lattitude, double longitude) {
String address = "";
Geocoder geocoder;
List<Address> addresses = null;
geocoder = new Geocoder(context, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(lattitude, longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
} catch (IOException e) {
e.printStackTrace();
}
cityR = "";
stateR = "";
String postalCode = "";
try {
if (addresses != null && addresses.size() > 0) {
address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
addressR = address;
String city = addresses.get(0).getLocality();
cityR = city;
String state = addresses.get(0).getAdminArea();
String district = addresses.get(0).getSubAdminArea();
stateR = state;
districtR = district;
String country = addresses.get(0).getCountryName();
postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
}
} catch (Exception e) {
e.printStackTrace();
}
if (postalCode == null)
return "";
else return postalCode;
}
/**
* Method to check if a GSTIN is valid. Checks the GSTIN format and the
* check digit is valid for the passed input GSTIN
*
* @param gstin
* @return boolean - valid or not
* @throws Exception
*/
public static boolean validGSTIN(String gstin) throws Exception {
boolean isValidFormat = false;
if (checkPattern(gstin, GSTINFORMAT_REGEX)) {
isValidFormat = verifyCheckDigit(gstin);
}
return isValidFormat;
}
public static boolean validPan(String s) throws Exception {
boolean isValid = false;
Pattern pattern = Pattern.compile("[A-Z]{5}[0-9]{4}[A-Z]{1}");
Matcher matcher = pattern.matcher(s);
// Check if pattern matches
if (matcher.matches()) {
isValid = true;
}
return isValid;
}
/**
* Method for checkDigit verification.
*
* @param gstinWCheckDigit
* @return
* @throws Exception
*/
private static boolean verifyCheckDigit(String gstinWCheckDigit) throws Exception {
Boolean isCDValid = false;
String newGstninWCheckDigit = getGSTINWithCheckDigit(
gstinWCheckDigit.substring(0, gstinWCheckDigit.length() - 1));
if (gstinWCheckDigit.trim().equals(newGstninWCheckDigit)) {
isCDValid = true;
}
return isCDValid;
}
/**
* Method to check if an input string matches the regex pattern passed
*
* @param inputval
* @param regxpatrn
* @return boolean
*/
public static boolean checkPattern(String inputval, String regxpatrn) {
boolean result = false;
if ((inputval.trim()).matches(regxpatrn)) {
result = true;
}
return result;
}
/**
* Method to get the check digit for the gstin (without checkdigit)
*
* @param gstinWOCheckDigit
* @return : GSTIN with check digit
* @throws Exception
*/
public static String getGSTINWithCheckDigit(String gstinWOCheckDigit) throws Exception {
int factor = 2;
int sum = 0;
int checkCodePoint = 0;
char[] cpChars;
char[] inputChars;
try {
if (gstinWOCheckDigit == null) {
throw new Exception("GSTIN supplied for checkdigit calculation is null");
}
cpChars = GSTN_CODEPOINT_CHARS.toCharArray();
inputChars = gstinWOCheckDigit.trim().toUpperCase().toCharArray();
int mod = cpChars.length;
for (int i = inputChars.length - 1; i >= 0; i--) {
int codePoint = -1;
for (int j = 0; j < cpChars.length; j++) {
if (cpChars[j] == inputChars[i]) {
codePoint = j;
}
}
int digit = factor * codePoint;
factor = (factor == 2) ? 1 : 2;
digit = (digit / mod) + (digit % mod);
sum += digit;
}
checkCodePoint = (mod - (sum % mod)) % mod;
return gstinWOCheckDigit + cpChars[checkCodePoint];
} finally {
inputChars = null;
cpChars = null;
}
}
private static final String[] tensNames = {
"",
" Ten",
" Twenty",
" Thirty",
" Forty",
" Fifty",
" Sixty",
" Seventy",
" Eighty",
" Ninety"
};
private static final String[] numNames = {
"",
" One",
" Two",
" Three",
" Four",
" Five",
" Six",
" Seven",
" Eight",
" Nine",
" Ten",
" Eleven",
" Twelve",
" Thirteen",
" Fourteen",
" Fifteen",
" Sixteen",
" Seventeen",
" Eighteen",
" Nineteen"
};
private static String convertLessThanOneThousand(int number) {
String soFar;
if (number % 100 < 20) {
soFar = numNames[number % 100];
number /= 100;
} else {
soFar = numNames[number % 10];
number /= 10;
soFar = tensNames[number % 10] + soFar;
number /= 10;
}
if (number == 0) return soFar;
return numNames[number] + " Hundred" + soFar;
}
public static String convert(long number) {
// 0 to 999 999 999 999
if (number == 0) {
return "zero";
}
String snumber = Long.toString(number);
// pad with "0"
String mask = "000000000000";
DecimalFormat df = new DecimalFormat(mask);
snumber = df.format(number);
// XXXnnnnnnnnn
int billions = Integer.parseInt(snumber.substring(0, 3));
// nnnXXXnnnnnn
int millions = Integer.parseInt(snumber.substring(3, 6));
// nnnnnnXXXnnn
int hundredThousands = Integer.parseInt(snumber.substring(6, 9));
// nnnnnnnnnXXX
int thousands = Integer.parseInt(snumber.substring(9, 12));
String tradBillions;
switch (billions) {
case 0:
tradBillions = "";
break;
case 1:
tradBillions = convertLessThanOneThousand(billions)
+ " Billion ";
break;
default:
tradBillions = convertLessThanOneThousand(billions)
+ " Billion ";
}
String result = tradBillions;
String tradMillions;
switch (millions) {
case 0:
tradMillions = "";
break;
case 1:
tradMillions = convertLessThanOneThousand(millions)
+ " Million ";
break;
default:
tradMillions = convertLessThanOneThousand(millions)
+ " Million ";
}
result = result + tradMillions;
String tradHundredThousands;
switch (hundredThousands) {
case 0:
tradHundredThousands = "";
break;
case 1:
tradHundredThousands = "One Thousand ";
break;
default:
tradHundredThousands = convertLessThanOneThousand(hundredThousands)
+ " Thousand ";
}
result = result + tradHundredThousands;
String tradThousand;
tradThousand = convertLessThanOneThousand(thousands);
result = result + tradThousand;
// remove extra spaces!
return result.replaceAll("^\\s+", "").replaceAll("\\b\\s{2,}\\b", " ");
}
}
Comments
Post a Comment