I am making app in which user can attach Image from gallery, capture from camera or attach PDF file so i want to send File using volley. I wrote MultipartRequest class in which i can pass bitmap by using ByArrayOutputStream. But now i want to send File. There is an sendLeave() in fragment which Fragment which sending file with other params. Only MultipartRequest class and SendLeave() is only related code for this question but other code for how file is created.
MultipartRequest Class
public class MultipartRequest extends Request<NetworkResponse> {
private final String twoHyphens = "--";
private final String lineEnd = "\r\n";
private final String boundary = "apiclient-" + System.currentTimeMillis();
private Response.Listener<NetworkResponse> mListener;
private Response.ErrorListener mErrorListener;
private Map<String, String> mHeaders;
public MultipartRequest(int method, String url,
Response.Listener<NetworkResponse> listener,
Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.mListener = listener;
this.mErrorListener = errorListener;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return (mHeaders != null) ? mHeaders : super.getHeaders();
}
#Override
public String getBodyContentType() {
return "multipart/form-data;boundary=" + boundary;
}
#Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
try {
// populate text payload
Map<String, String> params = getParams();
if (params != null && params.size() > 0) {
textParse(dos, params, getParamsEncoding());
}
// populate data byte payload
Map<String, DataPart> data = getByteData();
if (data != null && data.size() > 0) {
dataParse(dos, data);
}
// close multipart form data after text and file data
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* Custom method handle data payload.
*
* #return Map data part label with data byte
* #throws AuthFailureError
*/
protected Map<String, DataPart> getByteData() throws AuthFailureError {
return null;
}
#Override
protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
try {
return Response.success(
response,
HttpHeaderParser.parseCacheHeaders(response));
} catch (Exception e) {
return Response.error(new ParseError(e));
}
}
#Override
protected void deliverResponse(NetworkResponse response) {
mListener.onResponse(response);
}
#Override
public void deliverError(VolleyError error) {
mErrorListener.onErrorResponse(error);
}
/**
* Parse string map into data output stream by key and value.
*
* #param dataOutputStream data output stream handle string parsing
* #param params string inputs collection
* #param encoding encode the inputs, default UTF-8
* #throws IOException
*/
private void textParse(DataOutputStream dataOutputStream, Map<String, String> params, String encoding) throws IOException {
try {
for (Map.Entry<String, String> entry : params.entrySet()) {
buildTextPart(dataOutputStream, entry.getKey(), entry.getValue());
}
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException("Encoding not supported: " + encoding, uee);
}
}
/**
* Parse data into data output stream.
*
* #param dataOutputStream data output stream handle file attachment
* #param data loop through data
* #throws IOException
*/
private void dataParse(DataOutputStream dataOutputStream, Map<String, DataPart> data) throws IOException {
for (Map.Entry<String, DataPart> entry : data.entrySet()) {
buildDataPart(dataOutputStream, entry.getValue(), entry.getKey());
}
}
/**
* Write string data into header and data output stream.
*
* #param dataOutputStream data output stream handle string parsing
* #param parameterName name of input
* #param parameterValue value of input
* #throws IOException
*/
private void buildTextPart(DataOutputStream dataOutputStream, String parameterName, String parameterValue) throws IOException {
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + parameterName + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(parameterValue + lineEnd);
}
/**
* Write data file into header and data output stream.
*
* #param dataOutputStream data output stream handle data parsing
* #param dataFile data byte as DataPart from collection
* #param inputName name of data input
* #throws IOException
*/
private void buildDataPart(DataOutputStream dataOutputStream, DataPart dataFile, String inputName) throws IOException {
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" +
inputName + "\"; filename=\"" + dataFile.getFileName() + "\"" + lineEnd);
if (dataFile.getType() != null && !dataFile.getType().trim().isEmpty()) {
dataOutputStream.writeBytes("Content-Type: " + dataFile.getType() + lineEnd);
}
dataOutputStream.writeBytes(lineEnd);
ByteArrayInputStream fileInputStream = new ByteArrayInputStream(dataFile.getContent());
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024 * 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dataOutputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dataOutputStream.writeBytes(lineEnd);
}
class DataPart {
private String fileName;
private byte[] content;
private String type;
public DataPart() {
}
DataPart(String name, byte[] data) {
fileName = name;
content = data;
}
String getFileName() {
return fileName;
}
byte[] getContent() {
return content;
}
String getType() {
return type;
}
}
}
AttachDocument Fragment
public class LeaveCreate extends Fragment {
File files;
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
btnAttach.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Dialog dialog = new Dialog(getActivity());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_layout);
dialog.show();
Button btnGallery = (Button) dialog.findViewById(R.id.btnGallery);
Button btnFile = (Button) dialog.findViewById(R.id.btnFile);
Button btnCamera = (Button) dialog.findViewById(R.id.btnCamera);
btnGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
Intent pickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
startActivityForResult(pickIntent,1);
}
});
btnFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/pdf");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(Intent.createChooser(intent,"Select a File to Upload"),2);
}catch (android.content.ActivityNotFoundException ex){
Toast.makeText(getActivity(), "Please Install a File Manager",Toast.LENGTH_SHORT).show();
}
}
});
btnCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
String filename = "digimTemp.jpg";
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.Media.TITLE,filename);
mCapturedImageURI = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,contentValues);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,mCapturedImageURI);
startActivityForResult(cameraIntent,3);
}
});
}
});
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SendLeave();
}
});
return view;
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = data.getData();
String path = getRealPathFromURI(getActivity(),selectedImageUri);
// Toast.makeText(getBaseContext(),path,
// Toast.LENGTH_LONG).show();
files = new File(path.substring(0,path.lastIndexOf("/")),path.substring(path.lastIndexOf("/"),path.length()));
btnAttach.setText("Gallery");
Bitmap b = null;
try {
b = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), selectedImageUri);
} catch (IOException e) {
e.printStackTrace();
}
Drawable d = new BitmapDrawable(getResources(), b);
d.setBounds(0, 0, 60, 60);
btnAttach.setCompoundDrawables(d, null, null, null);
btnAttach.setCompoundDrawablePadding(20);
}
}
else if (requestCode == 2) {
if (resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = data.getData();
String path = null;
path = getPath(getActivity(),selectedImageUri);
Toast.makeText(getActivity().getBaseContext(),path,
Toast.LENGTH_LONG).show();
files = new File(path.substring(0,path.lastIndexOf("/")),path.substring(path.lastIndexOf("/"),path.length()));
btnAttach.setText(path.substring(path.lastIndexOf("/")+1,path.length()));
}
}
else if(requestCode == 3)
{
if (resultCode == Activity.RESULT_OK) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, null, null, null);
int column_index_data = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToLast();
String path = cursor.getString(column_index_data);
Bitmap photo = BitmapFactory.decodeFile(path);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
// Uri tempUri = getImageUri(getApplicationContext(), bitmap);
files = new File(path.substring(0,path.lastIndexOf("/")),path.substring(path.lastIndexOf("/"),path.length()));
if (Integer.parseInt(String.valueOf(files.length() / 1024)) > 100) {
// filesize=String.valueOf(files.length()/1048576)+" MB";
}
btnAttach.setText("Camera");
// attachment.setDrawableLe
Drawable d = new BitmapDrawable(getResources(), photo);
d.setBounds(0, 0, 60, 60);
btnAttach.setCompoundDrawables(d, null, null, null);
btnAttach.setCompoundDrawablePadding(20);
}
}
}
}
public void SendLeave(){
progressDialog.show();
MultipartRequest multipartRequest = new MultipartRequest(Request.Method.POST, SEND_LEAVE_URL, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("parent_id", SharedPreferenceManager.getmInstance(getActivity()).getID());
params.put("student_id",studentid);
params.put("reason",txtReason.getText().toString());
params.put("start_date",txtFromDate.getText().toString());
params.put("end_date",txtToDate.getText().toString());
int i=0;
for (String temp: teacherid){
params.put("teacher_id["+(i++)+"]", temp);
}
return params;
}
#Override
protected Map<String, MultipartRequest.DataPart> getByteData() {
Map<String, MultipartRequest.DataPart> params = new HashMap<>();
params.put("file", new MultipartRequest.DataPart());
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.<String, String>emptyMap())){
headers = new HashMap<String, String>();
}
MyApp.get().addSessionCookie(headers);
return headers;
}
};
RequestQueue queue = Volley.newRequestQueue(getContext());
queue.add(multipartRequest);
}
Volley doesn’t support multi part file
But there’s a customized library of volley called Volley Plus which supports multi part file
Or use http url connection to send file.
Follow this.
Using http url connection u can also show the upload progress easily
This is what I used to upload a PDF, but you can use it to any file. I used the same VolleyMultipartRequest, you just have to get the data from the file to upload it. Hope it helps you!
private void uploadPDF() {
VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(
Request.Method.POST,
url,
new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
//Handle response
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Handle error
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
//Params
return params;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
String pdfName = String.valueOf(System.currentTimeMillis() + ".pdf");
params.put("pdf", new DataPart(pdfName, getFileData()));
return params;
}
};
//I used this because it was sending the file twice to the server
volleyMultipartRequest.setRetryPolicy(
new DefaultRetryPolicy(
0,
-1,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
)
);
requestQueue.add(volleyMultipartRequest);
}
private byte[] getFileData() {
int size = (int) pdf.length();
byte[] bytes = new byte[size];
byte[] tmpBuff = new byte[size];
try (FileInputStream inputStream = new FileInputStream(pdf)) {
int read = inputStream.read(bytes, 0, size);
if (read < size) {
int remain = size - read;
while (remain > 0) {
read = inputStream.read(tmpBuff, 0, remain);
System.arraycopy(tmpBuff, 0, bytes, size - remain, read);
remain -= read;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return bytes;
}
Related
I'm trying to post some data using volley to a server.
The issue seems to with an encoded string image.
On this line
String name = namefield.getText().toString();
String age = agefield.getText().toString();
String gender = genderfield.getText().toString();
String color = colorfield.getText().toString();
String notes = notesfield.getText().toString();
String images = encodeImage(bitmap);
updatedetails(name, age, gender, color, notes, String.valueOf(owner), String.valueOf(id), images);
if I change image to empty string
updatedetails(name, age, gender, color, notes, String.valueOf(owner), String.valueOf(id), "");
then than the data sends to server, which is how I know the image is the problem.
I logged the image response and this is what I get:
Strings: /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAUAAk8DASIA
AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA
AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3
ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm
p6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEA
AwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSEx
BhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElK
U1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3
uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD+8LwX
/wAit4a/7F/R/wD0011z/wCrH4/+hVyPgv8A5Fbw1/2L+j/+mmuuf/Vj8f8A0KuHC/7rP5f+knDh
f91n8v8A0ksUUUV3HcFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQ
AUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAB
RRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQBxPgv/kVvDX/AGL+j/8Apprr
n/1Y/H/0KuR8F/8AIreGv+xf0f8A9NNdc/8Aqx+P/oVcOF/3Wfy/9JOHC/7rP5f+kliiivGvjx8b
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
while the other data response are normal like:
Strings: red
The logcat says the problem is here:
try {
JSONObject jsonObject = new JSONObject(result);
Log.i("Check", result);
Here's the relevant code:
public void updatedetails(final String name, final String age, final String gender, final String color, final String notes, final String owner, final String id, final String pet_image) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
progressDialog.setMessage("Updating pet details");
progressDialog.show();
try {
String url = "https://happy-paws.co.za/dogwalking/apis/v1/pet/update_pet.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
String result = response.toString();
// Log.d("zzzz","res "+result);
Toast.makeText(update.this, response, Toast.LENGTH_SHORT).show();
getDataResponse1(result);
Log.i("Check", result);
Log.i("Check", response);
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(update.this, error.getMessage(), Toast.LENGTH_SHORT).show();
Log.d("TAG", error.getMessage());
}
}) {
#Override
public byte[] getBody() throws com.android.volley.AuthFailureError {
String str = "{\"name\":\"" + name + "\",\"age\":\"" + age + "\",\"gender\":\"" + gender + "\",\"color\":\"" + color + "\",\"notes\":\"" + notes + "\",\"owner\":\"" + owner + "\",\"id\":\"" + id + "\",\"pet_image\":\"" + pet_image + "\"}";
return str.getBytes();
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
// params.put("email",email);
// params.put("password",password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
} catch (Exception e) {
//App.handleUncaughtException(e);
}
progressDialog.dismiss();
}
public void getDataResponse1(String result) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
progressDialog.setMessage("Please Wait.....");
progressDialog.show();
try {
JSONObject jsonObject = new JSONObject(result);
Log.i("Check", result);
JSONObject current = jsonObject.getJSONObject(result);
String message = current.getString("message");
String name = jsonObject.isNull("name") ? null : jsonObject.getString("name");
String age = jsonObject.isNull("age") ? null : jsonObject.getString("age");
String gender = jsonObject.isNull("gender") ? null : jsonObject.getString("gender");
String notes = jsonObject.isNull("notes") ? null : jsonObject.getString("notes");
String color = jsonObject.isNull("color") ? null : jsonObject.getString("color");
// String android_status=jsonObject.getString("android_status");
if (message.equals("Pet was updated.")) {
Toast.makeText(this, "" + message, Toast.LENGTH_SHORT).show();
// updatedetails(name, age, gender, color, notes, String.valueOf(owner), String.valueOf(id), pet_image);
} else {
Toast.makeText(this, "" + message, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
progressDialog.dismiss();
}
private void selectImage(Context context) {
final CharSequence[] options = {"Take Photo", "Choose from Gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose your profile picture");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
Intent takePicture = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);
} else if (options[item].equals("Choose from Gallery")) {
Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, 1);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_CANCELED) {
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK && data != null) {
bitmap = (Bitmap) data.getExtras().get("data");
profilepic.setImageBitmap(bitmap);
encodeImage(bitmap);
}
break;
case 1:
if (resultCode == RESULT_OK) {
bitmap = (Bitmap) data.getExtras().get("data");
Uri selectedImage = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(selectedImage);
bitmap = BitmapFactory.decodeStream(inputStream);
profilepic.setImageBitmap(bitmap);
encodeImage(bitmap);
// Glide.clear(profilepic);
} catch (FileNotFoundException e) {
Toast.makeText(update.this, "Pet added succesfully", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
}
public String encodeImage(Bitmap bitmap) {
ByteArrayOutputStream ba = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, ba);
byte[] imagebyte = ba.toByteArray();
encode = android.util.Base64.encodeToString(imagebyte, Base64.DEFAULT);
return encode;
}
And then where I submit:
updatebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = namefield.getText().toString();
String age = agefield.getText().toString();
String gender = genderfield.getText().toString();
String color = colorfield.getText().toString();
String notes = notesfield.getText().toString();
String images = encodeImage(bitmap);
updatedetails(name, age, gender, color, notes, String.valueOf(owner), String.valueOf(id), images);
Log.d("Strings",images );
Log.d("Strings",color );
image response is ok. you must set image data type as LONGTEXT or LONGBLOB on database server. but a better solution is to use Multipart Image Upload for upload image on server.
you can try with Uploading Images to Server android
I want to Upload file to server by selecting the file from file manager So I have opened file manager by clicking on Button using this code,
button_upload_attachment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] galleryPermissions = {android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (EasyPermissions.hasPermissions(CIBILCaptureandUPLOAD.this, galleryPermissions)) {
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 1);
} else {
EasyPermissions.requestPermissions(this, "Access for storage",
101, galleryPermissions);
}
}
});
and onActivityResult method i have done something like this to get path of the file and had make UploadToserver function for uploading
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//ImagesData = data;
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
Uri contentUri=data.getData();
Log.e("bbbbbbbbbbbbbb", contentUri.toString());
if(contentUri.toString().endsWith(".png")||contentUri.toString().endsWith("jpg") ||
contentUri.toString().endsWith(".pdf")){
photoFile= new File(contentUri.getPath());
if (photoFile.exists()) {
Log.e("photoFile", "File Exists");
}
if (photoFile != null) {
new AsyncTask<String, String, File>() {
ProgressDialog pd;
#Override
protected void onPreExecute() {
pd = ProgressDialog.show(CIBILCaptureandUPLOAD.this, "", "Compressing...");
Log.e("PreExecute", "Compressing");
}
#Override
protected File doInBackground(String[] params) {
return photoFile;
}
#Override
protected void onPostExecute(File result) {
pd.dismiss();
if (result != null) {
new CIBILCaptureandUPLOAD.UploadFileToServer().execute(result);
}
}
}.execute("");
}
}else {
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentUri,
filePathColumn, null, null, null);
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = "";
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
Log.e("PATH", filePath);
photoFile = new File(filePath);
if (photoFile.exists()) {
Log.e("photoFile", "File Exists");
}
if (photoFile != null) {
new AsyncTask<String, String, File>() {
ProgressDialog pd;
#Override
protected void onPreExecute() {
pd = ProgressDialog.show(CIBILCaptureandUPLOAD.this, "", "Compressing...");
Log.e("PreExecute", "Compressing");
}
#Override
protected File doInBackground(String[] params) {
return photoFile;
}
#Override
protected void onPostExecute(File result) {
pd.dismiss();
if (result != null) {
new CIBILCaptureandUPLOAD.UploadFileToServer().execute(result);
}
}
}.execute("");
}
}
}
It works well in other devices but in samsung devices i have got
java.io.FileNotFoundException: /document/primary:Xender/other/When Strangers Meet_ 3 in 1 Box - John Harker.pdf: open failed: ENOENT (No such file or directory)
And my upload code is
private class UploadFileToServer extends AsyncTask {
private static final String TAG = "UploadFileToServer";
// private ProgressBar progressBar;
// private String filePath = null;
// private TextView txtPercentage;
private ProgressDialog pd;
long totalSize = 0;
#Override
protected void onPreExecute() {
// setting progress bar to zero
// progressBar.setProgress(0);
pd = ProgressDialog.show(CIBILCaptureandUPLOAD.this, "", "Loading...");
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
// progressBar.setVisibility(View.VISIBLE);
// updating progress bar value
pd.setMessage("Loading..." + progress[0]);
// progressBar.setProgress(progress[0]);
// updating percentage value
// txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
#Override
protected String doInBackground(File... params) {
return uploadFile1(params[0]);
}
#SuppressWarnings("deprecation")
private String uploadFile1(File file) {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(AppUtill.URL_CIBIL_imageupload);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = file;// new File(filePath);
entity.addPart("image", new FileBody(sourceFile));
entity.addPart("mid", new StringBody(memberid));
entity.addPart("did", new StringBody("0"));
entity.addPart("fid", new StringBody(formtypeid));
if (app_loadid == null) {
SharedPreferences sharedPreferences = getSharedPreferences("LID", MODE_PRIVATE);
app_loadid = sharedPreferences.getString("lid", "");
entity.addPart("lid", new StringBody(app_loadid));
} else {
entity.addPart("lid", new StringBody(app_loadid));
}
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("statusCode +statusCode");
if (statusCode == 200) {
// Server response
System.out.println("statusCode +statusCode");
responseString = EntityUtils.toString(r_entity);
String success = String.valueOf(responseString.contains("1"));
if (success.matches("true")) {
uploadedFileCount++;
} else {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "File not uploaded. Please upload again...", Toast.LENGTH_SHORT).show();
}
});
}
} else {
responseString = "Error occurred! Http Status Code: " + statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
Log.e(TAG, "Response from server: " + result);
pd.dismiss();
if (uploadedFileCount == MAX_COUNT) {
AlertDialog.Builder alert = new AlertDialog.Builder(CIBILCaptureandUPLOAD.this);
alert.setTitle(R.string.app_name);
alert.setMessage("Reach to max upload limit");
alert.setCancelable(false);
alert.setPositiveButton("OK", null);
alert.create().show();
}
// showing the server response in an alert dialog
showAlert(result);
AppUtill.deleteFolderAndAllFile(CIBILCaptureandUPLOAD.this);
super.onPostExecute(result);
}
}
photoFile= new File(contentUri.getPath());
Have a look at the value of contentUri.getPath() and see that it is not a valid file system path.
Instead you should open an InputStream for the obtained uri and read the file content from the stream.
InputStream is = getContentResolver().openInputStream(contentUri);
I am uploading audio on soundcloud server but when i click upload button it throws FileNotFoundException.After uploading a response from server has to be generated.plss help me guys. please correct me if i am making mistake somewhere.
There are 2 situation in which upload function is performed.
1.Recording of only one page story audio and uloding it.(in this case the audio is being uploade).
2. Recording of more than one page story in which after uploading of 1st page audio the 2nd page will come as response from my server.(In this case its throwing FileNotFound Exception).
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String tag_string_req = "req_login";
StringRequest postStringRequest = new StringRequest(Request.Method.POST, SC_LOGIN_LINK,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG,"Reponse Check for sound upload login :"+response);
// Log.d(TAG,"Object Check :"+json);
try {
JSONObject json = new JSONObject(response);
access_token = json.getString("access_token");
expires_in = json.getString("expires_in");
refresh_token = json.getString("refresh_token");
// doFileUpload();
new AsyncTaskRunner().execute();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(AccessToken.this, error.toString(), Toast.LENGTH_LONG).show();
Log.e(TAG, "Error Response Check :" + error);
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("client_id", client_id);
params.put("client_secret",client_secret);
params.put("grant_type",grant_type);
params.put("username",username);
params.put("password",user_password);
Log.d(TAG, "Params :" + params);
return params;
}
}; AppController.getInstance().addToRequestQueue(postStringRequest, tag_string_req);
}
});
}
private void mergeAudioFiles(){
try {
File tempFolder = new File(mRawAudioFolder.getPath());
Movie[] movies = new Movie[tempFolder.listFiles().length];
int i = 0;
for (File saveTempFile : tempFolder.listFiles()) {
try {
movies[i] = MovieCreator.build(new FileDataSourceImpl(saveTempFile));
} catch (IOException e) {
e.printStackTrace();
}
i++;
}
final Movie finalMovie = new Movie();
List<Track> audioTracks = new ArrayList<>();
for (Movie movie : movies) {
for (Track track : movie.getTracks()) {
}
}
finalMovie.addTrack(new AppendTrack(audioTracks.toArray(new Track[audioTracks.size()])));
final Container container = new DefaultMp4Builder().build(finalMovie);
mergedFile = new File(mAudioFolder.getPath()+"/merged.3gp");
final FileOutputStream fos = new FileOutputStream(mergedFile);
FileChannel fc = new RandomAccessFile(mergedFile, "rw").getChannel();
container.writeContainer(fc);
fc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void createAudioFolder() {
File movieFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
mRawAudioFolder = new File(movieFile, "Temp");
mAudioFolder = new File(movieFile, "The Tagore Project");
if (!mAudioFolder.exists()) {
mAudioFolder.mkdirs();
}
if (!mRawAudioFolder.exists()) {
mRawAudioFolder.mkdirs();
}
}
public byte[] toByteArray(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int read = 0;
byte[] buffer = new byte[1024];
while (read != -1) {
read = in.read(buffer);
if (read != -1)
out.write(buffer,0,read);
}
out.close();
return out.toByteArray();
}
public void forwardtoOurServer() {
String tag_string_req = "req_login";
StringRequest postStringRequest = new StringRequest(Request.Method.POST, RECORD_COMPOSITION_API,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Audio Upload Response Check :" + response);
Log.d(TAG,"Object Check :"+response);
try {
JSONObject json = new JSONObject(response);
String code = json.getString("code");
if (String.valueOf(code).equals("200")) {
JSONObject upload = json.getJSONObject("upload");
JSONObject Booking = json.getJSONObject("upload").getJSONObject("Booking");
JSONObject Composition = json.getJSONObject("upload").getJSONObject("Composition");
JSONObject TableofContents = json.getJSONObject("upload").getJSONObject("TableOfContent");
String content = Composition.getString("content");
String pageno = Composition.getString("pageno");
String tocid = Composition.getString("table_of_content_id");
String wrd_count = Composition.getString("wordcount");
String tocName = TableofContents.getString("name");
} else {
String errorMsg = json.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error Response Check :" + error);
}
}) {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("data[Booking][id]",bookingId);
params.put("data[Booking][contributor_id]",contributor_id);
params.put("data[Booking][table_of_content_id]",tocId);
params.put("data[Booking][cdn_id]",vs_cdn_id);
params.put("data[Booking][secret_token]",secret_token);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Date now = new Date();
String strDate = sdf.format(now);
params.put("data[Booking][uploaded_on]",strDate);
Log.d(TAG, "Params :" + params);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
headers.put("UUID", device_uuid);
headers.put("APPID", "2A192A0C22");
headers.put("USERID", "1");
headers.put("PLATFORM", "Andriod");
headers.put("APP_REQUEST", "1");
headers.put("PLATFORMVERSION",androidOS);
return headers;
}
};
AppController.getInstance().addToRequestQueue(postStringRequest, tag_string_req);
}
public void MediaRecorderReady(){
mediaRecorder=new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(AudioSavePathInDevice);
}
public String CreateRandomAudioFileName(int string){
StringBuilder stringBuilder = new StringBuilder( string );
int i = 0 ;
while(i < string ) {
stringBuilder.append(RandomAudioFileName.
charAt(random.nextInt(RandomAudioFileName.length())));
i++ ;
}
return stringBuilder.toString();
}
private void requestPermission() {
ActivityCompat.requestPermissions(RecordComposition.this, new
String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode);
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length> 0) {
boolean StoragePermission = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean RecordPermission = grantResults[1] ==
PackageManager.PERMISSION_GRANTED;
if (StoragePermission && RecordPermission) {
Toast.makeText(RecordComposition.this, "Permission Granted",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(RecordComposition.this,"Permission Denied",Toast.LENGTH_LONG).show();
}
}
break;
}
}
public boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(),
WRITE_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(),
RECORD_AUDIO);
return result == PackageManager.PERMISSION_GRANTED &&
result1 == PackageManager.PERMISSION_GRANTED;
}
private class AsyncTaskRunner extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... params) {
doFileUpload();
return null;
}
}
private void doFileUpload(){
HttpURLConnection conn = null;
//DataOutputStream dos = null;
//DataInputStream inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "https://api.soundcloud.com/tracks";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(mergedFile);
// open a URL connection to the Servlet
URL url = new URL (urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
//Adding oauth token
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"oauth_token\""+lineEnd+lineEnd+access_token+lineEnd);
// dos.writeBytes(lineEnd);
//Adding Track title
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"track[title]\""+lineEnd+lineEnd+tocName+"by Contributor"+":"+" "+contributorName+lineEnd);
//Track taglist
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"track[tag_list]\""+lineEnd+lineEnd+"Tagore Project"+lineEnd);
//Add sharing
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"track[sharing]\""+lineEnd+lineEnd+"private"+lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"track[asset_data]\";filename=\"" + mergedFile + "\"" + lineEnd);
dos.writeBytes("Content-Type: audio/mpeg"+lineEnd+lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd+twoHyphens + boundary + twoHyphens + lineEnd);
fileInputStream.close();
dos.flush();
dos.close();
Log.e("Debug","File is written - "+mergedFile+" - "+conn.getResponseCode());
}
catch (MalformedURLException ex)
{
Log.e("Debug", "error: " + ex.getMessage(), ex);
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
}
catch (IOException ioe)
{
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
Toast.makeText(this, ioe.getMessage(), Toast.LENGTH_SHORT).show();
}
try {
BufferedReader inStream = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String str;
Log.e("Debug","Before while");
while (( str = inStream.readLine() ) != null)
{
Log.e("Debug","Server Response "+str);
JSONObject response = new JSONObject(str);
vs_cdn_id = response.getString("id");
secret_token = response.getString("secret_token");
forwardtoOurServer();
}
inStream.close();
}
catch (IOException ioex){
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception ex){
ex.printStackTrace();
}
}
Log:
File is written - /storage/emulated/0/Movies/The Tagore Project/merged.3gp - 500
error: https://api.soundcloud.com/tracks
java.io.FileNotFoundException: https://api.soundcloud.com/tracks
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java)
at com.showhow2.www.thetagoreproject.RecordComposition.doFileUpload(RecordComposition.java:923)
at com.showhow2.www.thetagoreproject.RecordComposition.access$2400(RecordComposition.java:73)
at com.showhow2.www.thetagoreproject.RecordComposition$AsyncTaskRunner.doInBackground(RecordComposition.java:829)
at com.showhow2.www.thetagoreproject.RecordComposition$AsyncTaskRunner.doInBackground(RecordComposition.java:824)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Give permission in menifest...
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Add this on your code in your Activity class
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ArrayList<String> names = new ArrayList<>();
ArrayList<Integer> types = new ArrayList<>();
//add item to manes and types array
ListViewAdapter customList = new ListViewAdapter(this, names, types);
list = (ListView) findViewById(R.id.lv);
list.setAdapter(customList);
}
This is ListViewAdapter class
public class ListViewAdapter extends ArrayAdapter<String> {
private ArrayList<String> names;
ArrayList<Integer> types;
private Activity context;
public ListViewAdapter(Activity context, ArrayList<String> names, ArrayList<Integer> types) {
super(context, R.layout.item_rating_rows, names);
this.context = context;
this.names = names;
this.types = types;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.item_rating_rows, null, true);
Button btn = (Button) listViewItem.findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("__onclick", "" + view.getId());
}
});
return listViewItem;
}
}
Hello before someone says that i shouldnt store in database as blob, well i need it i have my reasons. Last time i asked this only response i got was like dont store in database or something. Well here is my code thatone part works the other part doesnt works, the part that works is taking photo and displaying it in imageview , not working is uploading to mysql database. If more information is needed tell me i will edit answer. thank you in advance.
Code
Activity:
public class takefoto extends BaseNavegationActivity {
Button takebt, sendbt;
String ba1;
String mCurrentPhotoPath;
ImageView mFoto;
int CodServico;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.takefoto);
takebt = (Button) findViewById(R.id.takebt);
mFoto = (ImageView) findViewById(R.id.fotoser);
takebt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
captureImage();
}
});
sendbt = (Button) findViewById(R.id.sendbt);
sendbt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
upload();
}
});
Bundle extras = getIntent().getExtras();
CodServico=extras.getInt("CodServico");
Log.i("CODSERVICO",CodServico+"");
}
private void upload() {
Bitmap bm = BitmapFactory.decodeFile(mCurrentPhotoPath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 50, bao);
byte[] ba = bao.toByteArray();
ba1 = Base64.encodeToString(ba,Base64.DEFAULT);
// Upload image to server
ServerRequests serverRequests = new ServerRequests(takefoto.this);
serverRequests.storeFotoDataInBackground(ba1, CodServico, new GetUpdaterCallBack() {
#Override
public void done(String returnUser) {
if (returnUser.equalsIgnoreCase("sucesso")) {
Toast.makeText(getApplicationContext(),"Enviado!",Toast.LENGTH_SHORT).show();
} else{
showError();
}
}
});
}
private void captureImage() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, 100);
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100 && resultCode == RESULT_OK) {
setPic();
}
}
private void setPic() {
// Get the dimensions of the View
int targetW = mFoto.getWidth();
int targetH = mFoto.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
mFoto.setImageBitmap(bitmap);
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
Log.e("Getpath", "Cool" + mCurrentPhotoPath);
return image;
}
private void showError(){
android.app.AlertDialog.Builder dialogBuilder=new android.app.AlertDialog.Builder(getBaseContext());
dialogBuilder.setMessage("Ocorreu um erro, por favor tente novamente mais tarde.");
dialogBuilder.setPositiveButton("Ok", null);
dialogBuilder.show();
}
}
ServerResquest method:
public void storeFotoDataInBackground(String ba, int codservico,GetUpdaterCallBack userCallback){
progressDialog.show();
new StoreFotoDataAsyncTasck(ba, codservico, userCallback).execute();
}
public class StoreFotoDataAsyncTasck extends AsyncTask<Void, Void, String> {
String ba;
int CodServico;
GetUpdaterCallBack registerCallback;
public StoreFotoDataAsyncTasck(String ba1, int codservico,GetUpdaterCallBack registerCallback) {
this.ba = ba1;
this.CodServico=codservico;
this.registerCallback = registerCallback;
}
#Override
protected String doInBackground(Void... params) {
String retorno = null;
try {
URL url = new URL(SERVER_ADDRESS + "myphpfile.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("CodServico", this.CodServico+"")
.appendQueryParameter("Imagem", this.ba);
Log.i("IMAGEM",this.ba+" CodServico"+this.CodServico);
final String postParameters = builder.build().getEncodedQuery();
conn.setConnectTimeout(3000);
conn.setReadTimeout(3000);
conn.setRequestMethod("POST");
conn.setFixedLengthStreamingMode(postParameters.getBytes().length);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoInput(true);
conn.setDoOutput(true);
//send the POST out
PrintWriter pw = new PrintWriter(conn.getOutputStream());
pw.print(postParameters);
pw.close();
conn.connect();
String result = convertStreamToString(conn.getInputStream());
JSONObject jObject = new JSONObject(result);
if(jObject.length()!=0){
retorno= jObject.getString("estado");
}
} catch (Exception e) {
e.printStackTrace();
}
return retorno;
}
}
My php code:
<?php
$codservic=$_POST['CodServico'];
$image = $_POST['Imagem'];
$con = mysqli_connect("xxxxxxxxx","xxxxxxxx","xxxxxxxxx","xxxxxxxxxx") or die('Unable To connect');
$sql = "insert into xxxxxxxx (xxxxxxxx,xxxxxxxx) values(?,?)";
$stmt = mysqli_prepare($con,$sql);
mysqli_stmt_bind_param($stmt,"is",$codservic,$image);
$sucesso=mysqli_stmt_execute($stmt);
if($sucesso){
$estado = array();
$estado[estado] = "sucesso";
echo json_encode($estado);
}
?>
Well after lot's of search i got it finnaly to work for those who need it too i will post my code.
Main activity:
public class takefoto extends BaseNavegationActivity {
Button takebt, sendbt;
String ba1;
String mCurrentPhotoPath;
ImageView mFoto;
int CodServico;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.takefoto);
takebt = (Button) findViewById(R.id.takebt);
mFoto = (ImageView) findViewById(R.id.fotoser);
takebt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
captureImage();
}
});
sendbt = (Button) findViewById(R.id.sendbt);
sendbt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
upload();
}
});
Bundle extras = getIntent().getExtras();
CodServico=extras.getInt("CodServico");
Log.i("CODSERVICO",CodServico+"");
}
private void upload() {
Bitmap bm = BitmapFactory.decodeFile(mCurrentPhotoPath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 50, bao);
byte[] ba = bao.toByteArray();
Log.i("IMAGEM NAO CONVERTIDA",ba+"");
ba1 = Base64.encodeToString(ba,Base64.DEFAULT);
// Get image and
// Upload image to server
ServerRequests serverRequests = new ServerRequests(takefoto.this);
serverRequests.storeFotoDataInBackground(ba1, CodServico, new GetUpdaterCallBack() {
#Override
public void done(String returnUser) {
if (returnUser.equalsIgnoreCase("sucesso")) {
Toast.makeText(getApplicationContext(),"Enviado!",Toast.LENGTH_SHORT).show();
} else{
showError();
}
}
});
}
private void captureImage() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, 100);
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100 && resultCode == RESULT_OK) {
setPic();
}
}
private void setPic() {
// Get the dimensions of the View
int targetW = mFoto.getWidth();
int targetH = mFoto.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
mFoto.setImageBitmap(bitmap);
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
Log.e("Getpath", "Cool" + mCurrentPhotoPath);
return image;
}
private void showError(){
android.app.AlertDialog.Builder dialogBuilder=new android.app.AlertDialog.Builder(getBaseContext());
dialogBuilder.setMessage("Ocorreu um erro, por favor tente novamente mais tarde.");
dialogBuilder.setPositiveButton("Ok", null);
dialogBuilder.show();
}
}
Server requests method(the part of the insert with database):
#Override
protected String doInBackground(Void... params) {
String retorno = null;
try {
URL url = new URL(SERVER_ADDRESS + "yourphpfile.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("Value1", this.CodServico+"")
.appendQueryParameter("Image", this.ba);
Log.i("IMAGEM",""+this.ba);
final String postParameters = builder.build().getEncodedQuery();
conn.setConnectTimeout(3000);
conn.setReadTimeout(3000);
conn.setRequestMethod("POST");
conn.setFixedLengthStreamingMode(postParameters.getBytes().length);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoInput(true);
conn.setDoOutput(true);
//send the POST out
PrintWriter pw = new PrintWriter(conn.getOutputStream());
pw.print(postParameters);
pw.close();
conn.connect();
String result = convertStreamToString(conn.getInputStream());
JSONObject jObject = new JSONObject(result);
if(jObject.length()!=0){
retorno= jObject.getString("status");// if was sucess or not
}
} catch (Exception e) {
e.printStackTrace();
}
return retorno;
}
My php code:
<?php
$codservic=$_POST['Value1'];
$image = $_POST['Image'];
header("Content-type: image/jpg");
$img = base64_decode($image);
$con = mysqli_connect("your connection string") or die('Unable To connect');
$sql = "insert into yourtable (yourcamp1,image) values(?,?)";
$stmt = mysqli_prepare($con,$sql);
mysqli_stmt_bind_param($stmt,"is",$codservic,$img);
$sucesso=mysqli_stmt_execute($stmt);
$estado = array();
if($sucesso){
$estado[status] = "sucess";
echo json_encode($estado);
} else {
$estado[status] = "error";
echo json_encode($estado);
}
?>
What are the correct way to convert Uri image to Base64 String before send to server ?
public void update( final String claimType, final String Amount, final String Description, final String imageUri)
{
class updateImageAndText extends AsyncTask<Void,Void,String>{
// ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
// loading = ProgressDialog.show(Edit_Staff.this,"Updating...","Wait...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// loading.dismiss();
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
try {
Intent returnIntent = new Intent();
returnIntent.putExtra("ClaimType", claimType);
returnIntent.putExtra("Amount", Amount);
returnIntent.putExtra("Description", Description);
returnIntent.putExtra("photo", imageUri);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}catch(Exception e)
{
}
}
#Override
protected String doInBackground(Void... params) {
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put(Configs.KEY_ID, String.valueOf(ID));
Log.e("ID", ID + "");
hashMap.put(Configs.KEY_TYPE, claimType);
hashMap.put(Configs.KEY_AMOUNT, Amount);
hashMap.put(Configs.KEY_DESCRIPTION, Description);
if(imageUri != null){
Log.d("log", "photo " + imageUri);
hashMap.put(Configs.KEY_IMAGE,getStringImage(imageUri)); // error
}else{
Log.d("log", "photo is null " );
}
RequestHandler rh = new RequestHandler();
String s = rh.sendPostRequest(Configs.URL_UPDATEDE_IMAGE_TEXT,hashMap);
return s;
}
}
updateImageAndText ue = new updateImageAndText();
ue.execute();
}
public String getStringImage(Uri imgUri) {
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imgUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
} catch (Exception e) {
}
return "";
}
Error
Error:incompatible types: String cannot be converted to Uri
In update you are passing imageUri as a String:
public void update( final String claimType, final String Amount, final String Description, final String imageUri)
hashMap.put(Configs.KEY_IMAGE,getStringImage(imageUri)); // error because imageUri is a String
But your method expect a Uri not String:
public String getStringImage(Uri imgUri){...}