*********************swapnil photo pdf and data save java code************ package salesforce; import android.Manifest; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.provider.MediaStore; import android.text.Editable; import android.text.TextWatcher; import android.util.Base64; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.example.salesforce.R; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class CustomerMaster extends AppCompatActivity { private static final int CAMERA_PERMISSION_REQUEST = 3; private static final int PICK_PDF_REQUEST = 1; private static final int REQUEST_IMAGE_CAPTURE = 2; private static final String str = "CustomerMaster"; // private final String URL = "https://cpplgmp.com/php/android/SFInsert.php?type="+str; private final String PDF_UPLOAD_URL = "http://cpplgmp.com/php/android/pdf.php"; private final String IMAGE_UPLOAD_URL= "http://cpplgmp.com/php/android/photo.php"; private EditText cmNameofDistributor, cmAddress, cmTaluka, cmDistrict, cmPinCod, cmContactPerson, cmMobileNo, cmEmailID, cmFSSAILic, pdfEditText1, pdfEditText2, pdfEditText3; private Spinner cmDistributorType, cmDrugLicYesNo; private Button cmBTNSave, cmBTPhoto, PdfButton1, PdfButton2, PdfButton3; private TextView fileNameTextView; private ImageView imageView; private String nameofdistributor, distributortype, address, taluka, district, pincode, contactperson, mobileno, emailid, druglicyesno, fssailc; private Uri filePath, filePath2, filePath3, filePath1; ArrayList TypeDistributor = new ArrayList<>(); ArrayList Lic = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_customer_master); cmNameofDistributor = findViewById(R.id.CMNameofDistributor); cmDistributorType = findViewById(R.id.CMDistributorType); cmAddress = findViewById(R.id.CMAddress); cmTaluka = findViewById(R.id.CMTaluka); cmDistrict = findViewById(R.id.CMDistrict); cmPinCod = findViewById(R.id.CMPinCod); cmContactPerson = findViewById(R.id.CMContactPerson); cmMobileNo = findViewById(R.id.CMMobileNo); cmEmailID = findViewById(R.id.CMEmailID); cmDrugLicYesNo = findViewById(R.id.CMDrugLicYesNo); cmFSSAILic = findViewById(R.id.CMFSSAILic); PdfButton1 = findViewById(R.id.selectPdfButton1); PdfButton2 = findViewById(R.id.selectPdfButton2); PdfButton3 = findViewById(R.id.selectPdfButton3); pdfEditText1 = findViewById(R.id.cmEditText1); pdfEditText2 = findViewById(R.id.cmEditText2); pdfEditText3 = findViewById(R.id.cmEditText3); cmBTPhoto = findViewById(R.id.CMBTPhoto); imageView = findViewById(R.id.imageView); PdfButton1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectPdf(); } }); nameofdistributor = distributortype = address = taluka = district = pincode = contactperson = mobileno = emailid = druglicyesno = fssailc = ""; cmBTNSave = findViewById(R.id.CMBTNSave); cmBTNSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { nameofdistributor = cmNameofDistributor.getText().toString(); distributortype = cmDistributorType.getSelectedItem().toString(); address = cmAddress.getText().toString(); taluka = cmTaluka.getText().toString(); district = cmDistrict.getText().toString(); pincode = cmPinCod.getText().toString(); contactperson = cmContactPerson.getText().toString(); mobileno = cmMobileNo.getText().toString(); emailid = cmEmailID.getText().toString(); druglicyesno = cmDrugLicYesNo.getSelectedItem().toString(); fssailc = cmFSSAILic.getText().toString(); if (!nameofdistributor.equals("") && !distributortype.equals("") && !address.equals("") && !taluka.equals("") && !district.equals("") && !pincode.equals("") && !contactperson.equals("") && !mobileno.equals("") && !emailid.equals("") && !druglicyesno.equals("") && !fssailc.equals("")) { StringRequest stringRequest = new StringRequest(Request.Method.POST, IMAGE_UPLOAD_URL, new Response.Listener() { @Override public void onResponse(String response) { saveDataToDatabase(); uploadPdf(filePath, "http://cpplgmp.com/php/android/pdf.php" + "?name=" + nameofdistributor); Toast.makeText(CustomerMaster.this, "Data And PDF file Save Successfully", Toast.LENGTH_SHORT).show(); } private void saveDataToDatabase() { { StringRequest stringRequest = new StringRequest(Request.Method.POST, IMAGE_UPLOAD_URL, new Response.Listener() { @Override public void onResponse(String response) { // Handle the response from the server Toast.makeText(CustomerMaster.this, response, Toast.LENGTH_SHORT).show(); // Upload the PDF files after saving the data // uploadPdf(filePath, "http://cpplgmp.com/php/android/demo3.php"); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // Handle error Toast.makeText(getApplicationContext(), error.toString().trim(), Toast.LENGTH_SHORT).show(); } }); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), error.toString().trim(), Toast.LENGTH_SHORT).show(); } }) { @Override protected Map getParams() throws AuthFailureError { Map data = new HashMap<>(); // Use toString() to get the correct file paths // data.put("file1", filePath1.toString()); // data.put("file2", filePath2.toString()); // data.put("file3", filePath3.toString()); // Log.d("FileUpload", "File Path 1: " + filePath1); // Log.d("FileUpload", "File Path 2: " + filePath2); // Log.d("FileUpload", "File Path 3: " + filePath3); data.put("nameofdistributor", nameofdistributor); data.put("distributortype", distributortype); data.put("address", address); data.put("taluka", taluka); data.put("district", district); data.put("pincode", pincode); data.put("contactperson", contactperson); data.put("mobileno", mobileno); data.put("emailid", emailid); data.put("druglicyesno", druglicyesno); data.put("fssailc", fssailc); return data; } }; RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext()); requestQueue.add(stringRequest); } } }); cmBTPhoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dispatchTakePictureIntent(); } }); TypeDistributor.add("SELECT"); TypeDistributor.add("Distributor"); TypeDistributor.add("Retailer"); TypeDistributor.add("C&FA"); ArrayAdapter arrayDistributor = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, TypeDistributor); cmDistributorType.setAdapter(arrayDistributor); Lic.add("SELECT"); Lic.add("YES"); Lic.add("NO"); ArrayAdapter arrayLic = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, Lic); cmDrugLicYesNo.setAdapter(arrayLic); cmDrugLicYesNo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { String selectedCategory = (String) parent.getItemAtPosition(position); RelativeLayout.LayoutParams b = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); b.addRule(RelativeLayout.CENTER_HORIZONTAL); if (selectedCategory.equals("YES")) { findViewById(R.id.pdfSelectionLayout1).setVisibility(View.VISIBLE); cmBTPhoto.setVisibility(View.VISIBLE); imageView.setVisibility(View.VISIBLE); b.topMargin = 100; } else { findViewById(R.id.pdfSelectionLayout1).setVisibility(View.GONE); cmBTPhoto.setVisibility(View.GONE); imageView.setVisibility(View.GONE); b.topMargin = 10; } cmBTNSave.setLayoutParams(b); } @Override public void onNothingSelected(AdapterView parent) { // Do nothing here } }); } private void dispatchTakePictureIntent() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST); } else { launchCamera(); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == CAMERA_PERMISSION_REQUEST) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { launchCamera(); } else { Toast.makeText(this, "Camera permission denied", Toast.LENGTH_SHORT).show(); } } } private void launchCamera() { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(getPackageManager()) != null) { startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_PDF_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { // Handling PDF selection filePath = data.getData(); pdfEditText1.setText(getSelectedFileName(filePath)); } else if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { // Handling image capture Bundle extras = data.getExtras(); Bitmap imageBitmap = (Bitmap) extras.get("data"); imageView.setImageBitmap(imageBitmap); String encodedImage = encodeToBase64(imageBitmap); sendImageToServer(encodedImage); } } private String encodeToBase64(Bitmap imageBitmap) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] imageBytes = baos.toByteArray(); return Base64.encodeToString(imageBytes, Base64.DEFAULT); } // Add this method to send the encoded image to the server private void sendImageToServer(final String encodedImage) { StringRequest stringRequest = new StringRequest(Request.Method.POST, IMAGE_UPLOAD_URL, new Response.Listener() { @Override public void onResponse(String response) { // Handle the response from the server try { JSONObject jsonObject = new JSONObject(response); String status = jsonObject.getString("status"); String message = jsonObject.getString("message"); if ("success".equals(status)) { // Image uploaded successfully Toast.makeText(CustomerMaster.this, message, Toast.LENGTH_SHORT).show(); } else { // Image upload failed Toast.makeText(CustomerMaster.this, "Error: " + message, Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); // JSON parsing error Toast.makeText(CustomerMaster.this, "Error parsing server response.", Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // Handle error Toast.makeText(getApplicationContext(), error.toString().trim(), Toast.LENGTH_SHORT).show(); } }) { @Override protected Map getParams() throws AuthFailureError { Map data = new HashMap<>(); // Add any additional parameters you want to send to the server data.put("image", encodedImage); return data; } }; RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext()); requestQueue.add(stringRequest); } private void uploadPdf(Uri filePath, String url) { new UploadPdfTask().execute(String.valueOf(filePath), url); } private class UploadPdfTask extends AsyncTask { @Override protected String doInBackground(String... params) { String filePath = params[0]; String url = params[1]; try { URL urlObj = new URL(url); HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection(); connection.setRequestMethod("POST"); connection.setDoInput(true); connection.setDoOutput(true); String boundary = "===" + System.currentTimeMillis() + "==="; connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); OutputStream outputStream = connection.getOutputStream(); outputStream.write(("--" + boundary + "\r\n").getBytes()); outputStream.write(("Content-Disposition: form-data; name=\"file\"; filename=\"file.pdf\"\r\n").getBytes()); outputStream.write(("Content-Type: application/pdf\r\n").getBytes()); outputStream.write(("\r\n").getBytes()); InputStream fileInputStream = getContentResolver().openInputStream(Uri.parse(filePath)); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = fileInputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } fileInputStream.close(); outputStream.write(("\r\n").getBytes()); outputStream.write(("--" + boundary + "--\r\n").getBytes()); outputStream.close(); int responseCode = connection.getResponseCode(); Log.i("PdfResponseCode", String.valueOf(responseCode)); Log.i("PdfResponseMessage", connection.getResponseMessage()); if (responseCode == HttpURLConnection.HTTP_OK) { // Successful upload BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); connection.disconnect(); return response.toString(); } else { // Error in upload // Log the error details InputStream errorStream = connection.getErrorStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream)); String line; StringBuilder errorResponse = new StringBuilder(); while ((line = reader.readLine()) != null) { errorResponse.append(line); } Log.e("PdfUploadError", errorResponse.toString()); return "Error: " + errorResponse.toString(); } } catch (Exception e) { Log.e("PdfError", "Exception occurred", e); return "Error: " + e.getMessage(); } } @Override protected void onPostExecute(String result) { super.onPostExecute(result); // Handle the result of the upload here Log.d("PdfUploadResult", result); try { JSONObject jsonObject = new JSONObject(result); String status = jsonObject.getString("status"); String message = jsonObject.getString("message"); if ("success".equals(status)) { // File uploaded successfully Toast.makeText(CustomerMaster.this, message, Toast.LENGTH_SHORT).show(); } else { // File upload failed Toast.makeText(CustomerMaster.this, "Error: " + message, Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); // JSON parsing error // Toast.makeText(CustomerMaster.this, "Error parsing server response.", Toast.LENGTH_SHORT).show(); } } // @Override // protected void onPostExecute(String result) { // super.onPostExecute(result); // // Handle the result of the upload here // Log.d("PdfUploadResult", result); // Toast.makeText(CustomerMaster.this, result, Toast.LENGTH_SHORT).show(); // } } private void selectPdf() { Intent intent = new Intent(); intent.setType("application/pdf"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select PDF"), PICK_PDF_REQUEST ); } private String getSelectedFileName(Uri filePath) { // This function extracts the file name from the provided Uri String selectedFileName = null; if (filePath != null) { Cursor cursor = getContentResolver().query(filePath, null, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { int nameIndex = cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME); selectedFileName = cursor.getString(nameIndex); } cursor.close(); } } return selectedFileName; } // Similar modifications for getSelectedFileName2 and getSelectedFileName3 private String getSelectedFileName2(Uri filePath2) { // This function extracts the file name from the provided Uri String selectedFileName2 = null; if (filePath2 != null) { Cursor cursor = getContentResolver().query(filePath2, null, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { int nameIndex = cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME); selectedFileName2 = cursor.getString(nameIndex); } cursor.close(); } } return selectedFileName2; } // Similar modifications for getSelectedFileName2 and getSelectedFileName3 private String getSelectedFileName3(Uri filePath3) { // This function extracts the file name from the provided Uri String selectedFileName3 = null; if (filePath3 != null) { Cursor cursor = getContentResolver().query(filePath3, null, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { int nameIndex = cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME); selectedFileName3 = cursor.getString(nameIndex); } cursor.close(); } } return selectedFileName3; } } ********PHOTO PDF AND DATANOT SAVE PHP****** begin_transaction(); // Save the photo to the specified directory if (file_put_contents($photoPath, $photoData)) { // Insert data into customer_master table $insertSql = "INSERT INTO customer_master (name_of_distributor, distributor_type, address, taluka, district, pin_code, contact_person, mobile_no, email_id, drug_lic_Yes_No, fssai_lic, photo) VALUES ('$nameofdistributor', '$distributortype', '$address', '$taluka', '$district', '$pincode', '$contactperson', '$mobileno', '$emailid', '$druglicyesno', '$fssailc', '".$filename."')"; if ($conn->query($insertSql)) { // Update the photo name in the customer_master table $updateSql = "UPDATE customer_master SET photo ='".$filename."' WHERE name_of_distributor ='$nameofdistributor'"; if ($conn->query($updateSql)) { // Both operations successful, commit the transaction $conn->commit(); echo "Data and photo saved successfully."; } else { // Rollback the transaction if the update fails $conn->rollback(); echo "Failure: " . $conn->error; } } else { // Rollback the transaction if the insert fails $conn->rollback(); echo "Failure: " . $conn->error; } } else { // Rollback the transaction if saving photo fails $conn->rollback(); echo "Failed to save photo."; } } else { echo "Image not provided in the POST data."; } } else { echo json_encode(array("status" => "error", "message" => "Invalid request method.")); } ?> ******************PHOTO PDF AND DATANOT SAVE********* package salesforce; import android.Manifest; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.provider.MediaStore; import android.text.Editable; import android.text.TextWatcher; import android.util.Base64; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.example.salesforce.R; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class CustomerMaster extends AppCompatActivity { private static final int CAMERA_PERMISSION_REQUEST = 3; private static final int PICK_PDF_REQUEST = 1; private static final int REQUEST_IMAGE_CAPTURE = 2; private static final String str = "CustomerMaster"; // private final String URL = "https://cpplgmp.com/php/android/SFInsert.php?type="+str; private final String PDF_UPLOAD_URL = "http://cpplgmp.com/php/android/pdf.php"; private final String IMAGE_UPLOAD_URL= "http://cpplgmp.com/php/android/photo.php"; private EditText cmNameofDistributor, cmAddress, cmTaluka, cmDistrict, cmPinCod, cmContactPerson, cmMobileNo, cmEmailID, cmFSSAILic, pdfEditText1, pdfEditText2, pdfEditText3; private Spinner cmDistributorType, cmDrugLicYesNo; private Button cmBTNSave, cmBTPhoto, PdfButton1, PdfButton2, PdfButton3; private TextView fileNameTextView; private ImageView imageView; private String nameofdistributor, distributortype, address, taluka, district, pincode, contactperson, mobileno, emailid, druglicyesno, fssailc; private Uri filePath, filePath2, filePath3, filePath1; ArrayList TypeDistributor = new ArrayList<>(); ArrayList Lic = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_customer_master); cmNameofDistributor = findViewById(R.id.CMNameofDistributor); cmDistributorType = findViewById(R.id.CMDistributorType); cmAddress = findViewById(R.id.CMAddress); cmTaluka = findViewById(R.id.CMTaluka); cmDistrict = findViewById(R.id.CMDistrict); cmPinCod = findViewById(R.id.CMPinCod); cmContactPerson = findViewById(R.id.CMContactPerson); cmMobileNo = findViewById(R.id.CMMobileNo); cmEmailID = findViewById(R.id.CMEmailID); cmDrugLicYesNo = findViewById(R.id.CMDrugLicYesNo); cmFSSAILic = findViewById(R.id.CMFSSAILic); PdfButton1 = findViewById(R.id.selectPdfButton1); PdfButton2 = findViewById(R.id.selectPdfButton2); PdfButton3 = findViewById(R.id.selectPdfButton3); pdfEditText1 = findViewById(R.id.cmEditText1); pdfEditText2 = findViewById(R.id.cmEditText2); pdfEditText3 = findViewById(R.id.cmEditText3); cmBTPhoto = findViewById(R.id.CMBTPhoto); imageView = findViewById(R.id.imageView); PdfButton1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectPdf(); } }); nameofdistributor = distributortype = address = taluka = district = pincode = contactperson = mobileno = emailid = druglicyesno = fssailc = ""; cmBTNSave = findViewById(R.id.CMBTNSave); cmBTNSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { nameofdistributor = cmNameofDistributor.getText().toString(); distributortype = cmDistributorType.getSelectedItem().toString(); address = cmAddress.getText().toString(); taluka = cmTaluka.getText().toString(); district = cmDistrict.getText().toString(); pincode = cmPinCod.getText().toString(); contactperson = cmContactPerson.getText().toString(); mobileno = cmMobileNo.getText().toString(); emailid = cmEmailID.getText().toString(); druglicyesno = cmDrugLicYesNo.getSelectedItem().toString(); fssailc = cmFSSAILic.getText().toString(); if (!nameofdistributor.equals("") && !distributortype.equals("") && !address.equals("") && !taluka.equals("") && !district.equals("") && !pincode.equals("") && !contactperson.equals("") && !mobileno.equals("") && !emailid.equals("") && !druglicyesno.equals("") && !fssailc.equals("")) { StringRequest stringRequest = new StringRequest(Request.Method.POST, IMAGE_UPLOAD_URL, new Response.Listener() { @Override public void onResponse(String response) { saveDataToDatabase(); uploadPdf(filePath, "http://cpplgmp.com/php/android/pdf.php" + "?name=" + nameofdistributor); Toast.makeText(CustomerMaster.this, "Data And PDF file Save Successfully", Toast.LENGTH_SHORT).show(); } private void saveDataToDatabase() { { StringRequest stringRequest = new StringRequest(Request.Method.POST, IMAGE_UPLOAD_URL, new Response.Listener() { @Override public void onResponse(String response) { // Handle the response from the server Toast.makeText(CustomerMaster.this, response, Toast.LENGTH_SHORT).show(); // Upload the PDF files after saving the data // uploadPdf(filePath, "http://cpplgmp.com/php/android/demo3.php"); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // Handle error Toast.makeText(getApplicationContext(), error.toString().trim(), Toast.LENGTH_SHORT).show(); } }); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), error.toString().trim(), Toast.LENGTH_SHORT).show(); } }) { @Override protected Map getParams() throws AuthFailureError { Map data = new HashMap<>(); // Use toString() to get the correct file paths // data.put("file1", filePath1.toString()); // data.put("file2", filePath2.toString()); // data.put("file3", filePath3.toString()); // Log.d("FileUpload", "File Path 1: " + filePath1); // Log.d("FileUpload", "File Path 2: " + filePath2); // Log.d("FileUpload", "File Path 3: " + filePath3); // data.put("nameofdistributor", nameofdistributor); data.put("distributortype", distributortype); data.put("address", address); data.put("taluka", taluka); data.put("district", district); data.put("pincode", pincode); data.put("contactperson", contactperson); data.put("mobileno", mobileno); data.put("emailid", emailid); data.put("druglicyesno", druglicyesno); data.put("fssailc", fssailc); return data; } }; RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext()); requestQueue.add(stringRequest); } } }); cmBTPhoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dispatchTakePictureIntent(); } }); TypeDistributor.add("SELECT"); TypeDistributor.add("Distributor"); TypeDistributor.add("Retailer"); TypeDistributor.add("C&FA"); ArrayAdapter arrayDistributor = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, TypeDistributor); cmDistributorType.setAdapter(arrayDistributor); Lic.add("SELECT"); Lic.add("YES"); Lic.add("NO"); ArrayAdapter arrayLic = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, Lic); cmDrugLicYesNo.setAdapter(arrayLic); cmDrugLicYesNo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { String selectedCategory = (String) parent.getItemAtPosition(position); RelativeLayout.LayoutParams b = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); b.addRule(RelativeLayout.CENTER_HORIZONTAL); if (selectedCategory.equals("YES")) { findViewById(R.id.pdfSelectionLayout1).setVisibility(View.VISIBLE); cmBTPhoto.setVisibility(View.VISIBLE); imageView.setVisibility(View.VISIBLE); b.topMargin = 100; } else { findViewById(R.id.pdfSelectionLayout1).setVisibility(View.GONE); cmBTPhoto.setVisibility(View.GONE); imageView.setVisibility(View.GONE); b.topMargin = 10; } cmBTNSave.setLayoutParams(b); } @Override public void onNothingSelected(AdapterView parent) { // Do nothing here } }); } private void dispatchTakePictureIntent() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST); } else { launchCamera(); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == CAMERA_PERMISSION_REQUEST) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { launchCamera(); } else { Toast.makeText(this, "Camera permission denied", Toast.LENGTH_SHORT).show(); } } } private void launchCamera() { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(getPackageManager()) != null) { startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_PDF_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { // Handling PDF selection filePath = data.getData(); pdfEditText1.setText(getSelectedFileName(filePath)); } else if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { // Handling image capture Bundle extras = data.getExtras(); Bitmap imageBitmap = (Bitmap) extras.get("data"); imageView.setImageBitmap(imageBitmap); String encodedImage = encodeToBase64(imageBitmap); sendImageToServer(encodedImage); } } private String encodeToBase64(Bitmap imageBitmap) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] imageBytes = baos.toByteArray(); return Base64.encodeToString(imageBytes, Base64.DEFAULT); } // Add this method to send the encoded image to the server private void sendImageToServer(final String encodedImage) { StringRequest stringRequest = new StringRequest(Request.Method.POST, IMAGE_UPLOAD_URL, new Response.Listener() { @Override public void onResponse(String response) { // Handle the response from the server try { JSONObject jsonObject = new JSONObject(response); String status = jsonObject.getString("status"); String message = jsonObject.getString("message"); if ("success".equals(status)) { // Image uploaded successfully Toast.makeText(CustomerMaster.this, message, Toast.LENGTH_SHORT).show(); } else { // Image upload failed Toast.makeText(CustomerMaster.this, "Error: " + message, Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); // JSON parsing error Toast.makeText(CustomerMaster.this, "Error parsing server response.", Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // Handle error Toast.makeText(getApplicationContext(), error.toString().trim(), Toast.LENGTH_SHORT).show(); } }) { @Override protected Map getParams() throws AuthFailureError { Map data = new HashMap<>(); // Add any additional parameters you want to send to the server data.put("image", encodedImage); return data; } }; RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext()); requestQueue.add(stringRequest); } private void uploadPdf(Uri filePath, String url) { new UploadPdfTask().execute(String.valueOf(filePath), url); } private class UploadPdfTask extends AsyncTask { @Override protected String doInBackground(String... params) { String filePath = params[0]; String url = params[1]; try { URL urlObj = new URL(url); HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection(); connection.setRequestMethod("POST"); connection.setDoInput(true); connection.setDoOutput(true); String boundary = "===" + System.currentTimeMillis() + "==="; connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); OutputStream outputStream = connection.getOutputStream(); outputStream.write(("--" + boundary + "\r\n").getBytes()); outputStream.write(("Content-Disposition: form-data; name=\"file\"; filename=\"file.pdf\"\r\n").getBytes()); outputStream.write(("Content-Type: application/pdf\r\n").getBytes()); outputStream.write(("\r\n").getBytes()); InputStream fileInputStream = getContentResolver().openInputStream(Uri.parse(filePath)); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = fileInputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } fileInputStream.close(); outputStream.write(("\r\n").getBytes()); outputStream.write(("--" + boundary + "--\r\n").getBytes()); outputStream.close(); int responseCode = connection.getResponseCode(); Log.i("PdfResponseCode", String.valueOf(responseCode)); Log.i("PdfResponseMessage", connection.getResponseMessage()); if (responseCode == HttpURLConnection.HTTP_OK) { // Successful upload BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); connection.disconnect(); return response.toString(); } else { // Error in upload // Log the error details InputStream errorStream = connection.getErrorStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream)); String line; StringBuilder errorResponse = new StringBuilder(); while ((line = reader.readLine()) != null) { errorResponse.append(line); } Log.e("PdfUploadError", errorResponse.toString()); return "Error: " + errorResponse.toString(); } } catch (Exception e) { Log.e("PdfError", "Exception occurred", e); return "Error: " + e.getMessage(); } } @Override protected void onPostExecute(String result) { super.onPostExecute(result); // Handle the result of the upload here Log.d("PdfUploadResult", result); try { JSONObject jsonObject = new JSONObject(result); String status = jsonObject.getString("status"); String message = jsonObject.getString("message"); if ("success".equals(status)) { // File uploaded successfully Toast.makeText(CustomerMaster.this, message, Toast.LENGTH_SHORT).show(); } else { // File upload failed Toast.makeText(CustomerMaster.this, "Error: " + message, Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); // JSON parsing error // Toast.makeText(CustomerMaster.this, "Error parsing server response.", Toast.LENGTH_SHORT).show(); } } // @Override // protected void onPostExecute(String result) { // super.onPostExecute(result); // // Handle the result of the upload here // Log.d("PdfUploadResult", result); // Toast.makeText(CustomerMaster.this, result, Toast.LENGTH_SHORT).show(); // } } private void selectPdf() { Intent intent = new Intent(); intent.setType("application/pdf"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select PDF"), PICK_PDF_REQUEST ); } private String getSelectedFileName(Uri filePath) { // This function extracts the file name from the provided Uri String selectedFileName = null; if (filePath != null) { Cursor cursor = getContentResolver().query(filePath, null, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { int nameIndex = cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME); selectedFileName = cursor.getString(nameIndex); } cursor.close(); } } return selectedFileName; } // Similar modifications for getSelectedFileName2 and getSelectedFileName3 private String getSelectedFileName2(Uri filePath2) { // This function extracts the file name from the provided Uri String selectedFileName2 = null; if (filePath2 != null) { Cursor cursor = getContentResolver().query(filePath2, null, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { int nameIndex = cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME); selectedFileName2 = cursor.getString(nameIndex); } cursor.close(); } } return selectedFileName2; } // Similar modifications for getSelectedFileName2 and getSelectedFileName3 private String getSelectedFileName3(Uri filePath3) { // This function extracts the file name from the provided Uri String selectedFileName3 = null; if (filePath3 != null) { Cursor cursor = getContentResolver().query(filePath3, null, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { int nameIndex = cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME); selectedFileName3 = cursor.getString(nameIndex); } cursor.close(); } } return selectedFileName3; } } *********************save photo localy*********** private void saveImageLocally(Bitmap imageBitmap) { String fileName = "captured_image.jpg"; try { FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE); imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); fos.close(); // Display a message that the image has been saved Toast.makeText(this, "Image saved locally", Toast.LENGTH_SHORT).show(); } catch (Exception e) { e.printStackTrace(); } } ************************************* // private void uploadPhoto(Uri filePath, String url) { // new UploadPhotoTask().execute(filePath.toString(), url); // } // class UploadPhotoTask extends AsyncTask { // @Override // protected String doInBackground(String... params) { // String photoPath = params[0]; // String url = params[1]; // try { // URL urlObj = new URL(url); // HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection(); // connection.setRequestMethod("POST"); // connection.setDoInput(true); // connection.setDoOutput(true); // // String boundary = "===" + System.currentTimeMillis() + "==="; // connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); // // OutputStream outputStream = connection.getOutputStream(); // outputStream.write(("--" + boundary + "\r\n").getBytes()); // outputStream.write(("Content-Disposition: form-data; name=\"photo\"; filename=\"photo.jpg\"\r\n").getBytes()); // outputStream.write(("Content-Type: image/jpeg\r\n").getBytes()); // outputStream.write(("\r\n").getBytes()); // // InputStream photoInputStream = getContentResolver().openInputStream(Uri.parse(photoPath)); // byte[] photoBuffer = new byte[1024]; // int photoBytesRead; // while ((photoBytesRead = photoInputStream.read(photoBuffer)) != -1) { // outputStream.write(photoBuffer, 0, photoBytesRead); // } // photoInputStream.close(); // // outputStream.write(("\r\n").getBytes()); // outputStream.write(("--" + boundary + "--\r\n").getBytes()); // outputStream.close(); // // int responseCode = connection.getResponseCode(); // Log.i("ResponseCode", String.valueOf(responseCode)); // Log.i("ResponseMessage", connection.getResponseMessage()); // // BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); // String line; // StringBuilder response = new StringBuilder(); // while ((line = reader.readLine()) != null) { // response.append(line); // } // reader.close(); // // connection.disconnect(); // // return response.toString(); // // } catch (Exception e) { // Log.e("Error", "Exception occurred", e); // return "Error"; // } // } // // @Override // protected void onPostExecute(String result) { // super.onPostExecute(result); // // Handle the result of the photo upload here // Log.i("PhotoUploadResult", result); // } // } ************************************ ****************************************************************** package com.example; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.OpenableColumns; import android.view.View; import android.widget.Button; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.example.demo1.R; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; public class MainActivity2 extends AppCompatActivity { private static final int PICK_PDF_REQUEST = 1; private static final String PDF_UPLOAD_URL = "https://cpplgmp.com/php/android/demo3.php"; private byte[] pdfData; // Store the PDF content as bytes private Button selectPdfButton, uploadButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); selectPdfButton = findViewById(R.id.select_pdf_button); uploadButton = findViewById(R.id.upload_button); selectPdfButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pickPDF(); } }); uploadButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (pdfData != null) { uploadPDF(pdfData); } else { Toast.makeText(MainActivity2.this, "Please select a PDF file", Toast.LENGTH_SHORT).show(); } } }); } private void pickPDF() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("application/pdf"); startActivityForResult(Intent.createChooser(intent, "Select a PDF file"), PICK_PDF_REQUEST); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_PDF_REQUEST && resultCode == RESULT_OK && data != null) { Uri selectedPDF = data.getData(); pdfData = getPDFContent(selectedPDF); // Extract and display the file name String pdfFileName = getFileNameFromUri(selectedPDF); Toast.makeText(this, "Selected PDF: " + pdfFileName, Toast.LENGTH_SHORT).show(); selectPdfButton.setText(pdfFileName); } } private String getFileNameFromUri(Uri selectedPDF) { String result = null; if (selectedPDF != null) { String[] projection = {OpenableColumns.DISPLAY_NAME}; Cursor cursor = getContentResolver().query(selectedPDF, projection, null, null, null); if (cursor != null) { try { if (cursor.moveToFirst()) { int columnIndex = ((Cursor) cursor).getColumnIndex(OpenableColumns.DISPLAY_NAME); if (columnIndex != -1) { result = cursor.getString(columnIndex); } } } finally { cursor.close(); } } } return result; } private byte[] getPDFContent(Uri pdfUri) { try { ContentResolver contentResolver = getContentResolver(); InputStream inputStream = contentResolver.openInputStream(pdfUri); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { byteArrayOutputStream.write(buffer, 0, bytesRead); } return byteArrayOutputStream.toByteArray(); } catch (IOException e) { e.printStackTrace(); } return null; } private void uploadPDF(final byte[] pdfData) { StringRequest stringRequest = new StringRequest(Request.Method.POST, PDF_UPLOAD_URL, new Response.Listener() { @Override public void onResponse(String response) { Toast.makeText(MainActivity2.this, response, Toast.LENGTH_SHORT).show(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(MainActivity2.this, "Error uploading PDF: " + error.getMessage(), Toast.LENGTH_SHORT).show(); } }) { @Override public byte[] getBody() throws AuthFailureError { return pdfData; } }; RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext()); requestQueue.add(stringRequest); } } **************php********************* query($sql)){ echo "{\"status\":\"success\"}"; } else { echo "{\"status\":\"".$conn->error."\"}"; } $conn->close(); ?> ********************fragmentxml************* *********************************************pdf select code *************** package salesforce; import android.Manifest; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.text.Editable; import android.text.TextWatcher; import android.util.Base64; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.example.salesforce.R; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class CustomerMaster extends AppCompatActivity { private static final int CAMERA_PERMISSION_REQUEST = 3; private static final String TAG = "CustomerMaster"; private static final String str = "CustomerMaster"; private static final int CAMERA_CAPTURE_REQUEST_CODE = 0; private EditText cmNameofDistributor, cmAddress, cmTaluka, cmDistrict, cmPinCod, cmContactPerson, cmMobileNo, cmEmailID, cmFSSAILic,pdfEditText1,pdfEditText2,pdfEditText3; Spinner cmDistributorType, cmDrugLicYesNo; private final String URL = "https://cpplgmp.com/php/android/demo3.php?type="+str; ArrayList TypeDistributor = new ArrayList<>(); ArrayList Lic = new ArrayList<>(); private String nameofdistributor, distributortype, address, taluka, district, pincode, contactperson, mobileno, emailid, druglicyesno, fssailc; private Button cmBTNSave, cmBTPhoto, PdfButton1, PdfButton2, PdfButton3; private TextView fileNameTextView; private static final int PICK_PDF_REQUEST = 1; private Uri filePath,filePath2,filePath3,filePath1; private static final int REQUEST_IMAGE_CAPTURE = 2; // Use a unique request code for the camera private Uri imageUri; private ImageView imageView; Bitmap capturedPhoto; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_customer_master); cmNameofDistributor = findViewById(R.id.CMNameofDistributor); cmDistributorType = findViewById(R.id.CMDistributorType); cmAddress = findViewById(R.id.CMAddress); cmTaluka = findViewById(R.id.CMTaluka); cmDistrict = findViewById(R.id.CMDistrict); cmPinCod = findViewById(R.id.CMPinCod); cmContactPerson = findViewById(R.id.CMContactPerson); cmMobileNo = findViewById(R.id.CMMobileNo); cmEmailID = findViewById(R.id.CMEmailID); cmDrugLicYesNo = findViewById(R.id.CMDrugLicYesNo); cmFSSAILic = findViewById(R.id.CMFSSAILic); PdfButton1 = findViewById(R.id.selectPdfButton1); PdfButton2 = findViewById(R.id.selectPdfButton2); PdfButton3 = findViewById(R.id.selectPdfButton3); pdfEditText1 = findViewById(R.id.cmEditText1); pdfEditText2 = findViewById(R.id.cmEditText2); pdfEditText3 = findViewById(R.id.cmEditText3); cmBTPhoto = findViewById(R.id.CMBTPhoto); imageView = findViewById(R.id.imageView); PdfButton1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectPdf(0); } }); PdfButton2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectPdf(1); } }); PdfButton3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { selectPdf(2); } }); nameofdistributor = distributortype = address = taluka = district = pincode = contactperson = mobileno = emailid = druglicyesno = fssailc = ""; cmBTNSave = findViewById(R.id.CMBTNSave); cmBTNSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { nameofdistributor = cmNameofDistributor.getText().toString(); distributortype = cmDistributorType.getSelectedItem().toString(); address = cmAddress.getText().toString(); taluka = cmTaluka.getText().toString(); district = cmDistrict.getText().toString(); pincode = cmPinCod.getText().toString(); contactperson = cmContactPerson.getText().toString(); mobileno = cmMobileNo.getText().toString(); emailid = cmEmailID.getText().toString(); druglicyesno = cmDrugLicYesNo.getSelectedItem().toString(); fssailc = cmFSSAILic.getText().toString(); if (capturedPhoto != null) { String encodedPhoto = encodeToBase64(capturedPhoto); sendPhotoToServer(encodedPhoto); String fileName = "captured_photo.png"; File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), fileName); try (FileOutputStream fos = new FileOutputStream(file)) { capturedPhoto.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.flush(); fos.close(); // Now you can use the 'file' variable to get the path or upload it to the server // For example, String filePath = file.getAbsolutePath(); } catch (IOException e) { e.printStackTrace(); } } else { Toast.makeText(CustomerMaster.this, "No photo captured", Toast.LENGTH_SHORT).show(); } if (!nameofdistributor.equals("") && !distributortype.equals("") && !address.equals("") && !taluka.equals("") && !district.equals("") && !pincode.equals("") && !contactperson.equals("") && !mobileno.equals("") && !emailid.equals("") && !druglicyesno.equals("") && !fssailc.equals("")) { StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener() { @Override public void onResponse(String response) { uploadPdf(filePath, "http://cpplgmp.com/php/android/pdf.php"); Toast.makeText(CustomerMaster.this, response, Toast.LENGTH_SHORT).show(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), error.toString().trim(), Toast.LENGTH_SHORT).show(); } }) { @Override protected Map getParams() throws AuthFailureError { Map data = new HashMap<>(); data.put("nameofdistributor", nameofdistributor); data.put("distributortype", distributortype); data.put("address", address); data.put("taluka", taluka); data.put("district", district); data.put("pincode", pincode); data.put("contactperson", contactperson); data.put("mobileno", mobileno); data.put("emailid", emailid); data.put("druglicyesno", druglicyesno); data.put("fssailc", fssailc); return data; } }; RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext()); requestQueue.add(stringRequest); } } private void sendPhotoToServer(String encodedPhoto) { // Your server URL for photo upload String photoUploadUrl = "https://cpplgmp.com/php/android/demo3.php?type="+str; // Create a StringRequest to send the photo data to the server StringRequest photoRequest = new StringRequest(Request.Method.POST, photoUploadUrl, new Response.Listener() { @Override public void onResponse(String response) { // Handle the response from the server Toast.makeText(CustomerMaster.this, "Photo uploaded successfully", Toast.LENGTH_SHORT).show(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // Handle errors that occur during the request Toast.makeText(CustomerMaster.this, "Error uploading photo", Toast.LENGTH_SHORT).show(); } }) { @Override protected Map getParams() throws AuthFailureError { // Pass the encoded photo to the server as a POST parameter Map params = new HashMap<>(); params.put("photo", encodedPhoto); return params; } }; // Add the request to the Volley request queue RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext()); requestQueue.add(photoRequest); } }); TypeDistributor.add("SELECT"); TypeDistributor.add("Distributor"); TypeDistributor.add("Retailer"); TypeDistributor.add("C&FA"); ArrayAdapter arrayDistributor = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, TypeDistributor); cmDistributorType.setAdapter(arrayDistributor); Lic.add("SELECT"); Lic.add("YES"); Lic.add("NO"); ArrayAdapter arrayLic = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, Lic); cmDrugLicYesNo.setAdapter(arrayLic); cmDrugLicYesNo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { String selectedCategory = (String) parent.getItemAtPosition(position); RelativeLayout.LayoutParams b = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); b.addRule(RelativeLayout.CENTER_HORIZONTAL); if (selectedCategory.equals("YES")) { findViewById(R.id.pdfSelectionLayout1).setVisibility(View.VISIBLE); findViewById(R.id.pdfSelectionLayout2).setVisibility(View.VISIBLE); findViewById(R.id.pdfSelectionLayout3).setVisibility(View.VISIBLE); b.topMargin = 100; } else { findViewById(R.id.pdfSelectionLayout1).setVisibility(View.GONE); findViewById(R.id.pdfSelectionLayout2).setVisibility(View.GONE); findViewById(R.id.pdfSelectionLayout3).setVisibility(View.GONE); b.topMargin = 10; } cmBTNSave.setLayoutParams(b); } @Override public void onNothingSelected(AdapterView parent) { // Do nothing here } }); cmBTPhoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dispatchTakePictureIntent(); } }); // // Set a click listener for the camera button // cmBTPhoto.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // dispatchTakePictureIntent(); // } // }); } // Add a new method to handle launching the camera private void dispatchTakePictureIntent() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST); } else { // Permission is already granted, launch the camera launchCamera(); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == CAMERA_PERMISSION_REQUEST) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission granted, launch the camera launchCamera(); } else { // Permission denied, handle it as needed (e.g., show a message to the user) Toast.makeText(this, "Camera permission denied", Toast.LENGTH_SHORT).show(); } } } // Add a new method to handle launching the camera private void launchCamera() { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(getPackageManager()) != null) { startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); } } // @Override // protected void onActivityResult(int Code, int resultCode, Intent data) { // super.onActivityResult(Code, resultCode, data); // // if (Code == CAMERA_CAPTURE_REQUEST_CODE && resultCode == RESULT_OK) { // if (data != null && data.getExtras() != null) { // capturedPhoto = (Bitmap) data.getExtras().get("data"); // if (capturedPhoto != null) { // imageView.setImageBitmap(capturedPhoto); // } // } // } // } private String encodeToBase64(Bitmap image) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.PNG, 100, outputStream); byte[] byteArray = outputStream.toByteArray(); return Base64.encodeToString(byteArray, Base64.DEFAULT); } @Override protected void onActivityResult ( int requestCode, int resultCode, Intent data){ super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) { if (data != null && data.getExtras() != null) { capturedPhoto = (Bitmap) data.getExtras().get("data"); if (capturedPhoto != null) { imageView.setImageBitmap(capturedPhoto); imageView.setVisibility(View.VISIBLE); cmBTPhoto.setVisibility(View.GONE); } } } else if (requestCode >= PICK_PDF_REQUEST && requestCode <= PICK_PDF_REQUEST + 2 && resultCode == Activity.RESULT_OK && data != null) { filePath = data.getData(); int buttonNumber = requestCode - PICK_PDF_REQUEST; if (buttonNumber == 0) { filePath1 = filePath; pdfEditText1.setText(getSelectedFileName1(filePath)); } else if (buttonNumber == 1) { filePath2 = filePath; pdfEditText2.setText(getSelectedFileName2(filePath2)); } else if (buttonNumber == 2) { filePath3 = filePath; pdfEditText3.setText(getSelectedFileName3(filePath3)); } } else if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK && data != null) { // Handle photo capture Bundle extras = data.getExtras(); Bitmap imageBitmap = (Bitmap) extras.get("data"); // Display the captured image in an ImageView imageView.setImageBitmap(imageBitmap); imageView.setVisibility(View.VISIBLE); cmBTPhoto.setVisibility(View.GONE); // You can save the image to a file if needed // Save the image to a file, and then you can use the file's path } } private void uploadPdf(Uri filePath, String url) { new UploadPdfTask().execute(filePath.toString(), url); } private class UploadPdfTask extends AsyncTask { @Override protected String doInBackground(String... params) { String pdfPath = params[0]; String url = params[1]; try { URL urlObj = new URL(url); HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection(); connection.setRequestMethod("POST"); connection.setDoInput(true); connection.setDoOutput(true); String boundary = "===" + System.currentTimeMillis() + "==="; connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); OutputStream outputStream = connection.getOutputStream(); outputStream.write(("--" + boundary + "\r\n").getBytes()); outputStream.write(("Content-Disposition: form-data; name=\"file\"; filename=\"file.pdf\"\r\n").getBytes()); outputStream.write(("Content-Type: application/pdf\r\n").getBytes()); outputStream.write(("\r\n").getBytes()); InputStream fileInputStream = getContentResolver().openInputStream(Uri.parse(pdfPath)); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = fileInputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } fileInputStream.close(); outputStream.write(("\r\n").getBytes()); outputStream.write(("--" + boundary + "--\r\n").getBytes()); outputStream.close(); int responseCode = connection.getResponseCode(); Log.i("ResponseCode", String.valueOf(responseCode)); Log.i("ResponseMessage", connection.getResponseMessage()); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); connection.disconnect(); return response.toString(); } catch (Exception e) { Log.e("Error", "Exception occurred", e); return "Error"; } } @Override protected void onPostExecute(String result) { super.onPostExecute(result); // Handle the result of the upload here Toast.makeText(CustomerMaster.this, result, Toast.LENGTH_SHORT).show(); Log.i("Result", result); } } private void selectPdf(int buttonNumber) { Intent intent = new Intent(); intent.setType("application/pdf"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select PDF"), PICK_PDF_REQUEST + buttonNumber); } private String getSelectedFileName1(Uri filePath1) { // This function extracts the file name from the provided Uri String selectedFileName1 = null; if (filePath1 != null) { Cursor cursor = getContentResolver().query(filePath, null, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { int nameIndex = cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME); selectedFileName1 = cursor.getString(nameIndex); } cursor.close(); } } return selectedFileName1; } private String getSelectedFileName2(Uri filePath2) { // This function extracts the file name from the provided Uri String selectedFileName2 = null; if (filePath2 != null) { Cursor cursor = getContentResolver().query(filePath, null, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { int nameIndex = cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME); selectedFileName2 = cursor.getString(nameIndex); } cursor.close(); } } return selectedFileName2; } private String getSelectedFileName3(Uri filePath3) { // This function extracts the file name from the provided Uri String selectedFileName3 = null; if (filePath3 != null) { Cursor cursor = getContentResolver().query(filePath, null, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { int nameIndex = cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME); selectedFileName3 = cursor.getString(nameIndex); } cursor.close(); } } return selectedFileName3; } } *********************pdf PHP*************************** query($sql) === TRUE) { echo "The file has been uploaded successfully."; } else { echo "Error: " . $sql . "
" . $conn->error; } } else { echo "Sorry, there was an error uploading your file."; } ?> ********************last java code to pdf save******************* package salesforce; import android.Manifest; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.provider.MediaStore; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.example.salesforce.R; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class CustomerMaster extends AppCompatActivity { private static final int CAMERA_PERMISSION_REQUEST = 3; // private static final String TAG = "CustomerMaster"; private static final String str = "CustomerMaster"; private EditText cmNameofDistributor, cmAddress, cmTaluka, cmDistrict, cmPinCod, cmContactPerson, cmMobileNo, cmEmailID, cmFSSAILic,pdfEditText1,pdfEditText2,pdfEditText3; Spinner cmDistributorType, cmDrugLicYesNo; private final String URL = "https://cpplgmp.com/php/android/SFInsert.php?type="+str; ArrayList TypeDistributor = new ArrayList<>(); ArrayList Lic = new ArrayList<>(); private String nameofdistributor, distributortype, address, taluka, district, pincode, contactperson, mobileno, emailid, druglicyesno, fssailc; private Button cmBTNSave, cmBTPhoto, PdfButton1, PdfButton2, PdfButton3; private TextView fileNameTextView; private static final int PICK_PDF_REQUEST = 1; private Uri filePath,filePath2,filePath3,filePath1; private static final int REQUEST_IMAGE_CAPTURE = 2; // Use a unique request code for the camera private Uri imageUri; private ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_customer_master); cmNameofDistributor = findViewById(R.id.CMNameofDistributor); cmDistributorType = findViewById(R.id.CMDistributorType); cmAddress = findViewById(R.id.CMAddress); cmTaluka = findViewById(R.id.CMTaluka); cmDistrict = findViewById(R.id.CMDistrict); cmPinCod = findViewById(R.id.CMPinCod); cmContactPerson = findViewById(R.id.CMContactPerson); cmMobileNo = findViewById(R.id.CMMobileNo); cmEmailID = findViewById(R.id.CMEmailID); cmDrugLicYesNo = findViewById(R.id.CMDrugLicYesNo); cmFSSAILic = findViewById(R.id.CMFSSAILic); PdfButton1 = findViewById(R.id.selectPdfButton1); PdfButton2 = findViewById(R.id.selectPdfButton2); PdfButton3 = findViewById(R.id.selectPdfButton3); pdfEditText1 = findViewById(R.id.cmEditText1); pdfEditText2 = findViewById(R.id.cmEditText2); pdfEditText3 = findViewById(R.id.cmEditText3); cmBTPhoto = findViewById(R.id.CMBTPhoto); imageView = findViewById(R.id.imageView); // PdfButton1.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // selectPdf(0); // } // }); // // PdfButton2.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // selectPdf(1); // } // }); // // PdfButton3.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // selectPdf(2); // } // }); nameofdistributor = distributortype = address = taluka = district = pincode = contactperson = mobileno = emailid = druglicyesno = fssailc = ""; cmBTNSave = findViewById(R.id.CMBTNSave); cmBTNSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { nameofdistributor = cmNameofDistributor.getText().toString(); distributortype = cmDistributorType.getSelectedItem().toString(); address = cmAddress.getText().toString(); taluka = cmTaluka.getText().toString(); district = cmDistrict.getText().toString(); pincode = cmPinCod.getText().toString(); contactperson = cmContactPerson.getText().toString(); mobileno = cmMobileNo.getText().toString(); emailid = cmEmailID.getText().toString(); druglicyesno = cmDrugLicYesNo.getSelectedItem().toString(); fssailc = cmFSSAILic.getText().toString(); if (!nameofdistributor.equals("") && !distributortype.equals("") && !address.equals("") && !taluka.equals("") && !district.equals("") && !pincode.equals("") && !contactperson.equals("") && !mobileno.equals("") && !emailid.equals("") && !druglicyesno.equals("") && !fssailc.equals("")) { StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener() { @Override public void onResponse(String response) { // uploadPdf(filePath, filePath2, filePath3, "http://cpplgmp.com/php/android/demo3.php"); Toast.makeText(CustomerMaster.this, response, Toast.LENGTH_SHORT).show(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), error.toString().trim(), Toast.LENGTH_SHORT).show(); } }) { @Override protected Map getParams() throws AuthFailureError { Map data = new HashMap<>(); // Use toString() to get the correct file paths // data.put("file1", filePath1.toString()); // data.put("file2", filePath2.toString()); // data.put("file3", filePath3.toString()); data.put("nameofdistributor", nameofdistributor); data.put("distributortype", distributortype); data.put("address", address); data.put("taluka", taluka); data.put("district", district); data.put("pincode", pincode); data.put("contactperson", contactperson); data.put("mobileno", mobileno); data.put("emailid", emailid); data.put("druglicyesno", druglicyesno); data.put("fssailc", fssailc); return data; } }; RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext()); requestQueue.add(stringRequest); } } }); TypeDistributor.add("SELECT"); TypeDistributor.add("Distributor"); TypeDistributor.add("Retailer"); TypeDistributor.add("C&FA"); ArrayAdapter arrayDistributor = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, TypeDistributor); cmDistributorType.setAdapter(arrayDistributor); Lic.add("SELECT"); Lic.add("YES"); Lic.add("NO"); ArrayAdapter arrayLic = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, Lic); cmDrugLicYesNo.setAdapter(arrayLic); cmDrugLicYesNo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { String selectedCategory = (String) parent.getItemAtPosition(position); RelativeLayout.LayoutParams b = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); b.addRule(RelativeLayout.CENTER_HORIZONTAL); if (selectedCategory.equals("YES")) { findViewById(R.id.pdfSelectionLayout1).setVisibility(View.VISIBLE); findViewById(R.id.pdfSelectionLayout2).setVisibility(View.VISIBLE); findViewById(R.id.pdfSelectionLayout3).setVisibility(View.VISIBLE); b.topMargin = 100; } else { findViewById(R.id.pdfSelectionLayout1).setVisibility(View.GONE); findViewById(R.id.pdfSelectionLayout2).setVisibility(View.GONE); findViewById(R.id.pdfSelectionLayout3).setVisibility(View.GONE); b.topMargin = 10; } cmBTNSave.setLayoutParams(b); } @Override public void onNothingSelected(AdapterView parent) { // Do nothing here } }); cmBTPhoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dispatchTakePictureIntent(); } }); } // Add a new method to handle launching the camera private void dispatchTakePictureIntent() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST); } else { // Permission is already granted, launch the camera launchCamera(); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == CAMERA_PERMISSION_REQUEST) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission granted, launch the camera launchCamera(); } else { // Permission denied, handle it as needed (e.g., show a message to the user) Toast.makeText(this, "Camera permission denied", Toast.LENGTH_SHORT).show(); } } } // Add a new method to handle launching the camera private void launchCamera() { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(getPackageManager()) != null) { startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode >= PICK_PDF_REQUEST && requestCode <= PICK_PDF_REQUEST + 2 && resultCode == Activity.RESULT_OK && data != null) { filePath = data.getData(); int buttonNumber = requestCode - PICK_PDF_REQUEST ; if (buttonNumber == 0) { filePath1 = filePath; pdfEditText1.setText(getSelectedFileName1(filePath)); } else if (buttonNumber == 1) { filePath2 = filePath; pdfEditText2.setText(getSelectedFileName2(filePath2)); } else if (buttonNumber == 2) { filePath3 = filePath; pdfEditText3.setText(getSelectedFileName3(filePath3)); } } else if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK && data != null) { // Handle photo capture Bundle extras = data.getExtras(); Bitmap imageBitmap = (Bitmap) extras.get("data"); // Display the captured image in an ImageView imageView.setImageBitmap(imageBitmap); imageView.setVisibility(View.VISIBLE); cmBTPhoto.setVisibility(View.GONE); // You can save the image to a file if needed // Save the image to a file, and then you can use the file's path } } private void uploadPdf(Uri filePath, Uri filePath2, Uri filePath3, String url) { new UploadPdfTask().execute(String.valueOf(filePath), String.valueOf(filePath2), String.valueOf(filePath3), url); } // private void uploadPdf(Uri filePath, String url) { // new UploadPdfTask().execute(filePath.toString(), url); // } private class UploadPdfTask extends AsyncTask { @Override protected String doInBackground(String... params) { String pdfPath = params[0]; String url = params[1]; try { URL urlObj = new URL(url); HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection(); connection.setRequestMethod("POST"); connection.setDoInput(true); connection.setDoOutput(true); String boundary = "===" + System.currentTimeMillis() + "==="; connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); OutputStream outputStream = connection.getOutputStream(); outputStream.write(("--" + boundary + "\r\n").getBytes()); outputStream.write(("Content-Disposition: form-data; name=\"file\"; filename=\"file.pdf\"\r\n").getBytes()); outputStream.write(("Content-Type: application/pdf\r\n").getBytes()); outputStream.write(("\r\n").getBytes()); InputStream fileInputStream = getContentResolver().openInputStream(Uri.parse(pdfPath)); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = fileInputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } fileInputStream.close(); outputStream.write(("\r\n").getBytes()); outputStream.write(("--" + boundary + "--\r\n").getBytes()); outputStream.close(); int responseCode = connection.getResponseCode(); Log.i("ResponseCode", String.valueOf(responseCode)); Log.i("ResponseMessage", connection.getResponseMessage()); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); connection.disconnect(); return response.toString(); } catch (Exception e) { Log.e("Error", "Exception occurred", e); return "Error"; } } @Override protected void onPostExecute(String result) { super.onPostExecute(result); // Handle the result of the upload here Toast.makeText(CustomerMaster.this, result, Toast.LENGTH_SHORT).show(); Log.i("Result", result); } } private void selectPdf(int buttonNumber) { Intent intent = new Intent(); intent.setType("application/pdf"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select PDF"), PICK_PDF_REQUEST + buttonNumber); } private String getSelectedFileName1(Uri filePath) { // This function extracts the file name from the provided Uri String selectedFileName1 = null; if (filePath != null) { Cursor cursor = getContentResolver().query(filePath, null, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { int nameIndex = cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME); selectedFileName1 = cursor.getString(nameIndex); } cursor.close(); } } return selectedFileName1; } // Similar modifications for getSelectedFileName2 and getSelectedFileName3 private String getSelectedFileName2(Uri filePath2) { // This function extracts the file name from the provided Uri String selectedFileName2 = null; if (filePath2 != null) { Cursor cursor = getContentResolver().query(filePath2, null, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { int nameIndex = cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME); selectedFileName2 = cursor.getString(nameIndex); } cursor.close(); } } return selectedFileName2; } // Similar modifications for getSelectedFileName2 and getSelectedFileName3 private String getSelectedFileName3(Uri filePath3) { // This function extracts the file name from the provided Uri String selectedFileName3 = null; if (filePath3 != null) { Cursor cursor = getContentResolver().query(filePath3, null, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { int nameIndex = cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME); selectedFileName3 = cursor.getString(nameIndex); } cursor.close(); } } return selectedFileName3; } } ***********************************save user data******************** //package salesforce; // //import android.app.Activity; //import android.content.Intent; //import android.content.pm.PackageManager; //import android.database.Cursor; //import android.graphics.Bitmap; //import android.net.Uri; //import android.os.AsyncTask; //import android.os.Bundle; //import android.provider.MediaStore; //import android.text.Editable; //import android.text.TextWatcher; //import android.util.Log; //import android.view.View; //import android.view.ViewGroup; //import android.widget.AdapterView; //import android.widget.ArrayAdapter; //import android.widget.Button; //import android.widget.EditText; //import android.widget.ImageView; //import android.widget.RelativeLayout; //import android.widget.Spinner; //import android.widget.TextView; //import android.widget.Toast; //import androidx.annotation.NonNull; //import androidx.appcompat.app.AppCompatActivity; //import androidx.core.app.ActivityCompat; //import androidx.core.content.ContextCompat; //import com.android.volley.AuthFailureError; //import com.android.volley.Request; //import com.android.volley.RequestQueue; //import com.android.volley.Response; //import com.android.volley.VolleyError; //import com.android.volley.toolbox.StringRequest; //import com.android.volley.toolbox.Volley; ////import com.example.salesforce.Manifest; //import com.example.salesforce.R; // //import java.io.BufferedReader; //import java.io.InputStream; //import java.io.InputStreamReader; //import java.io.OutputStream; //import java.net.HttpURLConnection; //import java.net.URL; //import java.util.ArrayList; //import java.util.HashMap; //import java.util.Map; // //public class CustomerMaster extends AppCompatActivity { // private static final int CAMERA_PERMISSION_REQUEST = 3; // private static final String str = "CustomerMaster"; // private static final int REQUEST_IMAGE_CAPTURE =0 ; // private static final int PICK_PDF_REQUEST = 1; // private EditText cmNameofDistributor, cmAddress, cmTaluka, cmDistrict, cmPinCod, // cmContactPerson, cmMobileNo, cmEmailID, cmFSSAILic,pdfEditText1,pdfEditText2,pdfEditText3; // Spinner cmDistributorType, cmDrugLicYesNo; // private final String URL = "https://cpplgmp.com/php/android/SFInsert.php?type=" + str; // // ArrayList TypeDistributor = new ArrayList<>(); // ArrayList Lic = new ArrayList<>(); // private String nameofdistributor, distributortype, address, taluka, district, pincode, contactperson, mobileno, emailid, druglicyesno, fssailc; // private Button cmBTNSave, cmBTPhoto,PdfButton1,PdfButton2,PdfButton3; // private ImageView imageView; // private Uri filePath,filePath2,filePath3,filePath1; // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_customer_master); // // cmNameofDistributor = findViewById(R.id.CMNameofDistributor); // cmDistributorType = findViewById(R.id.CMDistributorType); // cmAddress = findViewById(R.id.CMAddress); // cmTaluka = findViewById(R.id.CMTaluka); // cmDistrict = findViewById(R.id.CMDistrict); // cmPinCod = findViewById(R.id.CMPinCod); // cmContactPerson = findViewById(R.id.CMContactPerson); // cmMobileNo = findViewById(R.id.CMMobileNo); // cmEmailID = findViewById(R.id.CMEmailID); // cmDrugLicYesNo = findViewById(R.id.CMDrugLicYesNo); // cmFSSAILic = findViewById(R.id.CMFSSAILic); // cmBTPhoto = findViewById(R.id.CMBTPhoto); // imageView = findViewById(R.id.imageView); // PdfButton1 = findViewById(R.id.selectPdfButton1); // PdfButton2 = findViewById(R.id.selectPdfButton2); // PdfButton3 = findViewById(R.id.selectPdfButton3); // nameofdistributor = distributortype = address = taluka = district = pincode = contactperson = mobileno = emailid = druglicyesno = fssailc = ""; // cmBTNSave = findViewById(R.id.CMBTNSave); // cmBTNSave.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // saveDataToDatabase(); // uploadPdf(filePath, "http://cpplgmp.com/php/android/pdf.php"); // } // }); // PdfButton1.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // selectPdf(0); // } // }); // // PdfButton2.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // selectPdf(1); // } // }); // // PdfButton3.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // selectPdf(2); // } // }); // TypeDistributor.add("SELECT"); // TypeDistributor.add("Distributor"); // TypeDistributor.add("Retailer"); // TypeDistributor.add("C&FA"); // ArrayAdapter arrayDistributor = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, TypeDistributor); // cmDistributorType.setAdapter(arrayDistributor); // Lic.add("SELECT"); // Lic.add("YES"); // Lic.add("NO"); // ArrayAdapter arrayLic = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, Lic); // cmDrugLicYesNo.setAdapter(arrayLic); // // cmDrugLicYesNo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { // @Override // public void onItemSelected(AdapterView parent, View view, int position, long id) { // String selectedCategory = (String) parent.getItemAtPosition(position); // RelativeLayout.LayoutParams b = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); // b.addRule(RelativeLayout.CENTER_HORIZONTAL); // // if (selectedCategory.equals("YES")) { // // Show relevant UI components // } else { // // Hide relevant UI components // } // // cmBTNSave.setLayoutParams(b); // } // @Override // public void onNothingSelected(AdapterView parent) { // // Do nothing here // } // }); // cmDrugLicYesNo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { // @Override // public void onItemSelected(AdapterView parent, View view, int position, long id) { // String selectedCategory = (String) parent.getItemAtPosition(position); // RelativeLayout.LayoutParams b = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); // b.addRule(RelativeLayout.CENTER_HORIZONTAL); // // if (selectedCategory.equals("YES")) { // findViewById(R.id.pdfSelectionLayout1).setVisibility(View.VISIBLE); // findViewById(R.id.pdfSelectionLayout2).setVisibility(View.VISIBLE); // findViewById(R.id.pdfSelectionLayout3).setVisibility(View.VISIBLE); // b.topMargin = 100; // } else { // findViewById(R.id.pdfSelectionLayout1).setVisibility(View.GONE); // findViewById(R.id.pdfSelectionLayout2).setVisibility(View.GONE); // findViewById(R.id.pdfSelectionLayout3).setVisibility(View.GONE); // b.topMargin = 10; // } // cmBTNSave.setLayoutParams(b); // } // // @Override // public void onNothingSelected(AdapterView parent) { // // Do nothing here // } // }); // // // } // // @Override // public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { // super.onRequestPermissionsResult(requestCode, permissions, grantResults); // if (requestCode == CAMERA_PERMISSION_REQUEST) { // if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // launchCamera(); // } else { // Toast.makeText(this, "Camera permission denied", Toast.LENGTH_SHORT).show(); // } // } // } // // private void launchCamera() { // Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // if (takePictureIntent.resolveActivity(getPackageManager()) != null) { // startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); // } // } // // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // super.onActivityResult(requestCode, resultCode, data); // // if (requestCode >= PICK_PDF_REQUEST && requestCode <= PICK_PDF_REQUEST + 2 && resultCode == Activity.RESULT_OK && data != null) { // filePath = data.getData(); // int buttonNumber = requestCode - PICK_PDF_REQUEST ; // // if (buttonNumber == 0) { // // filePath1 = filePath; // pdfEditText1.setText(getSelectedFileName1(filePath)); // } else if (buttonNumber == 1) { // filePath2 = filePath; // pdfEditText2.setText(getSelectedFileName2(filePath2)); // } else if (buttonNumber == 2) { // filePath3 = filePath; // pdfEditText3.setText(getSelectedFileName3(filePath3)); // } // } // // else if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK && data != null) { // // Handle photo capture // Bundle extras = data.getExtras(); // Bitmap imageBitmap = (Bitmap) extras.get("data"); // // // Display the captured image in an ImageView // imageView.setImageBitmap(imageBitmap); // imageView.setVisibility(View.VISIBLE); // cmBTPhoto.setVisibility(View.GONE); // // // You can save the image to a file if needed // // Save the image to a file, and then you can use the file's path // } // } // private void uploadPdf(Uri filePath, String url) { // new UploadPdfTask().execute(filePath.toString(), url); // } // private class UploadPdfTask extends AsyncTask { // // @Override // protected String doInBackground(String... params) { // String pdfPath = params[0]; // String url = params[1]; // try { // // URL urlObj=new URL(url); // HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection(); // connection.setRequestMethod("POST"); // connection.setDoInput(true); // connection.setDoOutput(true); // // String boundary = "===" + System.currentTimeMillis() + "==="; // connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); // // OutputStream outputStream = connection.getOutputStream(); // outputStream.write(("--" + boundary + "\r\n").getBytes()); // outputStream.write(("Content-Disposition: form-data; name=\"file\"; filename=\"file.pdf\"\r\n").getBytes()); // outputStream.write(("Content-Type: application/pdf\r\n").getBytes()); // outputStream.write(("\r\n").getBytes()); // // InputStream fileInputStream = getContentResolver().openInputStream(Uri.parse(pdfPath)); // byte[] buffer = new byte[1024]; // int bytesRead; // while ((bytesRead = fileInputStream.read(buffer)) != -1) { // outputStream.write(buffer, 0, bytesRead); // } // fileInputStream.close(); // // outputStream.write(("\r\n").getBytes()); // outputStream.write(("--" + boundary + "--\r\n").getBytes()); // outputStream.close(); // // int responseCode = connection.getResponseCode(); // Log.i("ResponseCode", String.valueOf(responseCode)); // Log.i("ResponseMessage", connection.getResponseMessage()); // // BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); // String line; // StringBuilder response = new StringBuilder(); // while ((line = reader.readLine()) != null) { // response.append(line); // } // reader.close(); // // connection.disconnect(); // // return response.toString(); // // } catch (Exception e) { // Log.e("Error", "Exception occurred", e); // return "Error"; // } // } // } // // private void saveDataToDatabase() { // nameofdistributor = cmNameofDistributor.getText().toString(); // distributortype = cmDistributorType.getSelectedItem().toString(); // address = cmAddress.getText().toString(); // taluka = cmTaluka.getText().toString(); // district = cmDistrict.getText().toString(); // pincode = cmPinCod.getText().toString(); // contactperson = cmContactPerson.getText().toString(); // mobileno = cmMobileNo.getText().toString(); // emailid = cmEmailID.getText().toString(); // druglicyesno = cmDrugLicYesNo.getSelectedItem().toString(); // fssailc = cmFSSAILic.getText().toString(); // // if (!nameofdistributor.equals("") && !distributortype.equals("") && !address.equals("") // && !taluka.equals("") && !district.equals("") && !pincode.equals("") && !contactperson.equals("") && !mobileno.equals("") // && !emailid.equals("") && !druglicyesno.equals("") && !fssailc.equals("")) { // StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener() { // @Override // public void onResponse(String response) { // Toast.makeText(CustomerMaster.this, response, Toast.LENGTH_SHORT).show(); // } // }, new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // Toast.makeText(getApplicationContext(), error.toString().trim(), Toast.LENGTH_SHORT).show(); // } // }) { // @Override // protected Map getParams() throws AuthFailureError { // Map data = new HashMap<>(); // data.put("nameofdistributor", nameofdistributor); // data.put("distributortype", distributortype); // data.put("address", address); // data.put("taluka", taluka); // data.put("district", district); // data.put("pincode", pincode); // data.put("contactperson", contactperson); // data.put("mobileno", mobileno); // data.put("emailid", emailid); // data.put("druglicyesno", druglicyesno); // data.put("fssailc", fssailc); // return data; // } // }; // RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext()); // requestQueue.add(stringRequest); // } // } // private void selectPdf(int buttonNumber) { // Intent intent = new Intent(); // intent.setType("application/pdf"); // intent.setAction(Intent.ACTION_GET_CONTENT); // startActivityForResult(Intent.createChooser(intent, "Select PDF"), PICK_PDF_REQUEST + buttonNumber); // } // private String getSelectedFileName1(Uri filePath) { // // This function extracts the file name from the provided Uri // String selectedFileName1 = null; // if (filePath != null) { // Cursor cursor = getContentResolver().query(filePath, null, null, null, null); // if (cursor != null) { // if (cursor.moveToFirst()) { // int nameIndex = cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME); // selectedFileName1 = cursor.getString(nameIndex); // } // cursor.close(); // } // } // return selectedFileName1; // } // //// Similar modifications for getSelectedFileName2 and getSelectedFileName3 // // private String getSelectedFileName2(Uri filePath2) { // // This function extracts the file name from the provided Uri // String selectedFileName2 = null; // if (filePath2 != null) { // Cursor cursor = getContentResolver().query(filePath2, null, null, null, null); // if (cursor != null) { // if (cursor.moveToFirst()) { // int nameIndex = cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME); // selectedFileName2 = cursor.getString(nameIndex); // } // cursor.close(); // } // } // return selectedFileName2; // } // //// Similar modifications for getSelectedFileName2 and getSelectedFileName3 // // private String getSelectedFileName3(Uri filePath3) { // // This function extracts the file name from the provided Uri // String selectedFileName3 = null; // if (filePath3 != null) { // Cursor cursor = getContentResolver().query(filePath3, null, null, null, null); // if (cursor != null) { // if (cursor.moveToFirst()) { // int nameIndex = cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME); // selectedFileName3 = cursor.getString(nameIndex); // } // cursor.close(); // } // } // return selectedFileName3; // } //}