Send the captured image to the web server in android - java

I want to send the captured image with the help of intent and send image to the remote server. I am using following code:
String image_str;
String URL =**************/image.php?;
ArrayList<NameValuePair> nameValuePairs;
imageview.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
TakePhoto();
}
});
private void TakePhoto() {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);
}
BitmapFactory.Options btmapOptions;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == RESULT_OK) {
if (data != null) {
/* photo = (Bitmap) data.getExtras().get("data");
imageview.setImageBitmap(photo); *//* this is image view where you want to set image*/
Log.d("camera ---- > ", "" + data.getExtras().get("data"));
Toast.makeText(getApplicationContext(), getLastImageId(), Toast.LENGTH_LONG).show();
btmapOptions = new BitmapFactory.Options();
photo = BitmapFactory.decodeFile( getLastImageId(), btmapOptions);
imageview.setImageBitmap(photo);
}
// sendImg();
dialog = ProgressDialog.show(surakhaActivity.this, "", "Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
}
});
sendImg();
// Toast.makeText(getBaseContext(), response, Toast.LENGTH_LONG).show();
}
}).start();
}
}
private String getLastImageId() {
final String[] imageColumns = { MediaStore.Images.Media._ID,
MediaStore.Images.Media.DATA };
final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
Cursor imageCursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns,
null, null, imageOrderBy);
if (imageCursor.moveToFirst()) {
int id = imageCursor.getInt(imageCursor
.getColumnIndex(MediaStore.Images.Media._ID));
String fullPath = imageCursor.getString(imageCursor
.getColumnIndex(MediaStore.Images.Media.DATA));
imageCursor.close();
return fullPath;
} else {
return "no path";
}
}
InputStream inputStream;
File f;
public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException {
String res = "";
StringBuffer buffer = new StringBuffer();
inputStream = response.getEntity().getContent();
int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
Toast.makeText(surakhaActivity.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();
if (contentLength < 0) {
}
else {
byte[] data = new byte[512];
int len = 0;
try {
while (-1 != (len = inputStream.read(data)) ) {
buffer.append(new String(data, 0, len)); //converting to string and appending to stringbuffer…..
}
}
catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close(); // closing the stream…..
}
catch (IOException e) {
e.printStackTrace();
}
res = buffer.toString(); // converting stringbuffer to string…..
// Toast.makeText(MainActivity.this, "Result : " + res, Toast.LENGTH_LONG).show();
}
return res;
}
public void sendImg() {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
byte [] byte_arr = stream.toByteArray();
image_str = Base64.encodeBytes(byte_arr);
nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("imgdata",image_str));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
the_string_response = convertResponseToString(response);
// editor.putString("imgRes", the_string_response);editor.commit();
Toast.makeText(surakhaActivity.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();
}
catch(Exception e) {
Toast.makeText(surakhaActivity.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();
}
dialog.dismiss();
this.finish();
}
}
But capturing the image and send progress dialog runs infinite and image is not sent.

This looks fishy...
dialog = ProgressDialog.show(surakhaActivity.this, "", "Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
}
});
sendImg();
// Toast.makeText(getBaseContext(), response, Toast.LENGTH_LONG).show();
}
}).start();
Can you put a "Log" on the sendImg() method to see if it ever gets called?

Related

Android Studios Uploading pictures into intern database

Im trying to develope a function so i can upload pictures into my intern database in Android Studios. Has somebody an idea how i can solve this?
Well , first thing you need to add two button to select picture and to submit upload picture something like ..
Button Buttonlog;
Button Buttonbro;
ProgressBar progressBar;
private TextView messageText;
private TextView file-token-name;
private ProgressDialog dialog = null;
private String upLoadServerUri = null;
private String imagepath=null;
private ImageView imageview;
private static final int PICK_IMAGE_GALLERY = 1;
#SuppressLint("ClickableViewAccessibility")
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main15);
file-token-name=findViewById(R.id.filename);
file-token-name.setVisibility(View.GONE);
Buttonbro = findViewById(R.id.button_selectpic);
Buttonbro.setVisibility(View.VISIBLE);
Buttonbro.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (ActivityCompat.checkSelfPermission(MainActivity15.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity15.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PICK_IMAGE_GALLERY);
} else {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, PICK_IMAGE_GALLERY);
}
} catch (Exception e) {
e.printStackTrace();
}
loadGallery();
}
});
progressBar = findViewById(R.id.progress);
imageview = findViewById(R.id.imageView_pic);
upLoadServerUri = "https://www.yoursite.net/upljsonfile.php";
Buttonlog.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View v) {
final String file1;
file1=file-token-name.getText().toString();
//Start ProgressBar first (Set visibility VISIBLE)
progressBar.setVisibility(View.VISIBLE);
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
//Starting Write and Read data with URL
//Creating array for parameters
String[] field = new String[1];
field[0] = "file1";
//Creating array for data
final String[] data = new String[1];
data[0] = file1;
if (!isFinishing()) {
PutData putData = new PutData("https://www.yorwebsite.net/post-to-database-file-name.php", "POST", field, data);
if (putData.startPut()) {
if (putData.onComplete()) {
progressBar.setVisibility(View.GONE);
String result = putData.getResult();
//End ProgressBar (Set visibility to GONE
if (result.equals("Post Succssefl")) {
if (!file1.equals("")) {
dialog = ProgressDialog.show(MainActivity15.this, "", "Uploading file...", true);
messageText.setText("uploading started.....");
// dialog = new ProgressDialog(MainActivity15.this);
// dialog.setMessage("Uploading File");
// dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setIndeterminate(true);
dialog.setMax(100);
dialog.show();
new Thread(new Runnable() {
public void run() {
uploadFile(imagepath);
}
}).start();
if (isFinishing()) {
if (dialog != null) {
dialog.dismiss();
dialog = null;
}
}
} else {
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), MainActivity11.class);
startActivity(i);
finish();
}
} else {
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
}
}
isFinishing();
}
}
}
}); //End Write and Read data with URL
}
});
}
And then our loadGallery() func
private void loadGallery() {
Intent choose = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(choose, PICK_IMAGE_GALLERY);
}
after that you have to allow permission take your image select path something like ..
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressLint("Recycle")
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
assert cursor != null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
if (requestCode == PICK_IMAGE_GALLERY) {// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, PICK_IMAGE_GALLERY);
} //do something like displaying a message that he didn`t allow the app to access gallery and you wont be able to let him select from gallery
}
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#SuppressLint({"SetTextI18n", "NewApi"})
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_GALLERY && data != null && resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = data.getData();
assert selectedImageUri != null;
imagepath = getPath(selectedImageUri);
Bitmap bitmap = BitmapFactory.decodeFile(imagepath);
imageview.setImageBitmap(bitmap);
messageText.setText("Uploading file path:" + imagepath);
String uriString = selectedImageUri.toString();
File myFile = new File(uriString);
String displayName;
if (uriString.startsWith("content://")) {
try (Cursor cursor = getContentResolver().query(selectedImageUri, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
file-token-name.setText(displayName);
}
}
} else if (uriString.startsWith("file://")) {
displayName = myFile.getName();
file-token-name.setText(displayName);
}
}
}
now we add our upload file func something like ..
#SuppressLint("LongLogTag")
public void uploadFile(String sourceFileUri) {
HttpURLConnection conn;
DataOutputStream dos;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"+imagepath);
runOnUiThread(new Runnable() {
#SuppressLint("SetTextI18n")
public void run() {
messageText.setText("Source File not exist :"+ imagepath);
}
});
}
else
{
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("file", sourceFileUri);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
+ sourceFileUri + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
int sentBytes=0;
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
sentBytes += bufferSize;
int progres =(bytesRead * 100 / bytesAvailable);
new Thread(
// do your stuff
new publishProgress(progres)
).start();
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
int serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+" C:/xamp/wamp/fileupload/uploads";
messageText.setText(msg);
Toast.makeText(MainActivity15.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
Intent i = new Intent(getApplicationContext(), MainActivity11.class);
startActivity(i);
finish();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
#SuppressLint("SetTextI18n")
public void run() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(MainActivity15.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
#SuppressLint("SetTextI18n")
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(MainActivity15.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
}
dialog.dismiss();
} // End else block
}
fainaly .. our tow php file one to upload our file"upljsonfile.php",And second to post our file name to database "post-to-database-file-name.php", like code bellow ..
the first file "upljsonfile.php" :
<?php
$response = array();
if (empty($_FILES) || $_FILES['file']['error']) {
$response["code"] = 2;
$response["message"] = "failed to move uploaded file";
echo json_encode($response);
}
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
$fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : $_FILES["file"]["name"];
$filePath = "uploadfiles/$fileName";
// Open temp file
$out = #fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
if ($out) {
// Read binary input stream and append it to temp file
$in = #fopen($_FILES['file']['tmp_name'], "rb");
if ($in) {
while ($buff = fread($in, 4096))
fwrite($out, $buff);
} else
$response["code"] = 2;
$response["message"] = "Oops! Failed to open input Stream error occurred.";
echo json_encode($response);
#fclose($in);
#fclose($out);
#unlink($_FILES['file']['tmp_name']);
} else
$response["code"] = 2;
$response["message"] = "Oops! Failed to open output error occurred.";
echo json_encode($response);
// Check if file has been uploaded
if (!$chunks || $chunk == $chunks - 1) {
// Strip the temp .part suffix off
rename("{$filePath}.part", $filePath);
}
$response["code"] = 2;
$response["message"] = "successfully uploaded";
echo json_encode($response);
?>
and the second file "post-to-database-file-name.php :
<?php
require "databasemob.php";
$db = new DataBase();
if (isset($_POST['file1']) ) {
if ($db->dbConnect()) {
if ($db->filenamepost("filename", $_POST['file1'])) {
echo "Post Succssefl";
} else echo "Some error !";
} else echo "Error: Database connection";
} else echo "All fields are required";
?>
and the databasemob.php :
<?php
require "DataBaseConfig.php";
class DataBase
{
public $connect;
public $data;
private $sql;
protected $servername;
protected $username;
protected $password;
protected $databasename;
public function __construct()
{
$this->connect = null;
$this->data = null;
$this->sql = null;
$dbc = new DataBaseConfig();
$this->servername = $dbc->servername;
$this->username = $dbc->username;
$this->password = $dbc->password;
$this->databasename = $dbc->databasename;
}
function dbConnect()
{
$this->connect = mysqli_connect($this->servername, $this->username, $this->password, $this->databasename);
return $this->connect;
}
function prepareData($data)
{
return mysqli_real_escape_string($this->connect, stripslashes(htmlspecialchars($data)));
}
function filenamepost($table, $file1)
{
$file1 = $this->prepareData($file1);
$ssq="SET NAMES 'utf8mb4';";
mysqli_query($this->connect,$ssq);
$this->sql =
"INSERT INTO " . $table . " (`file1`) VALUES ('" . $file1 . "')";
if (mysqli_query($this->connect, $this->sql)) {
return true;
} else return false;
}
}
?>
last file DataBaseConfig.php :
<?php
class DataBaseConfig
{
public $servername;
public $username;
public $password;
public $databasename;
public function __construct()
{
$this->servername = 'localhost';
$this->username = 'username';
$this->password = 'pass#';
$this->databasename = 'filename';
}
}
?>
this way its work by take ur file name from file Uri from phone and prosses for tow way by uploading file and post file to your database ,, hope it help you :)

How to upload video in android using volley

I am trying to upload a video on the server, I didn't anything on this, please suggest
I can upload the text, that's working,
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://54.146.132.94/webservices/target_response",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(mContext, "" + response, Toast.LENGTH_SHORT).show();
Log.i("error", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(mContext, "" + error.toString(), Toast.LENGTH_SHORT).show();
Log.i("error", error.toString());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("I_trails", String.valueOf(itr));
params.put("E_trails", String.valueOf(et));
params.put("D_trails", String.valueOf(dt));
params.put("N_trails", String.valueOf(nt));
params.put("user_id", String.valueOf(get_id));
params.put("target_id", String.valueOf(get_target_id));
params.put("session_date", date);
params.put("data_mode", data_mode);
params.put("mode", mode);
params.put("link", link);
// params.put("video", selectedPath);
params.put("time", time_upload_real);
params.put("location_id", LocID);
params.put("No_of_trails", String.valueOf(notr));
/*params.put("comment", my_comment);*/
return params;
}
};
// Adding the StringRequest object into requestQueue.
requestQueue.add(stringRequest);
here the code to upload video, please let me know how to upload this video with the data, that I am uploading.
if (null != selectedPath && !selectedPath.isEmpty()){
Toast.makeText(mContext, "selected path: "+selectedPath, Toast.LENGTH_SHORT).show();
new Thread(new Runnable() {
#Override
public void run() {
//creating new thread to handle Http Operations
uploadFile(selectedPath);
}
}).start();
then,
public int uploadFile(final String selectedPath){
int serverResponseCode = 0;
HttpURLConnection connection;
DataOutputStream dataOutputStream;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead,bytesAvailable,bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File selectedFile = new File(selectedPath);
try {
FileInputStream fileInputStream = new FileInputStream(selectedFile);
URL url = new URL("http://54.146.132.94/webservices/target_response");
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);//Allow Inputs
connection.setDoOutput(true);//Allow Outputs
connection.setUseCaches(false);//Don't use a cached Copy
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("video",selectedPath);
//creating new dataoutputstream
dataOutputStream = new DataOutputStream(connection.getOutputStream());
//writing bytes to data outputstream
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"video\";filename=\""
+ selectedPath + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
//returns no. of bytes present in fileInputStream
bytesAvailable = fileInputStream.available();
//selecting the buffer size as minimum of available bytes or 1 MB
bufferSize = Math.min(bytesAvailable,maxBufferSize);
//setting the buffer as byte array of size of bufferSize
buffer = new byte[bufferSize];
//reads bytes from FileInputStream(from 0th index of buffer to buffersize)
bytesRead = fileInputStream.read(buffer,0,bufferSize);
//loop repeats till bytesRead = -1, i.e., no bytes are left to read
while (bytesRead > 0){
//write the bytes read from inputstream
dataOutputStream.write(buffer,0,bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = fileInputStream.read(buffer,0,bufferSize);
}
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
//closing the input and output streams
fileInputStream.close();
dataOutputStream.flush();
dataOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// dialog.dismiss();
return serverResponseCode;
}
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_GALLERY);
and after selecting video
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) return;
if (requestCode == PICK_FROM_GALLERY) {
Uri aa = data.getData();
mVideoURI = Uri.parse(String.valueOf(aa));
}
}
dont forget to use private Uri mVideoURI;
at top
inside your post volley method use :
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
/// photo field in link
if (mVideoURI != null) {
params.put("video", new DataPart("file_avatar.mp4", UploadHelper.getFileDataFromDrawable(getActivity(), mVideoURI)));
}
return params;
}
UPDATE
1- CREATE BroadcastHelper CLASS :
public class BroadcastHelper {
public static final String BROADCAST_EXTRA_METHOD_NAME = "INPUT_METHOD_CHANGED";
public static final String ACTION_NAME = "hassan.scott";
private static final String UPDATE_LOCATION_METHOD = "update";
public static void sendInform(Context context, String method) {
Intent intent = new Intent();
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void sendInform(Context context, String method, Intent intent) {
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
2- Send intent from your adapter
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent url = new Intent("url");
url ("url_adapter",item.get(position).getURL());
BroadcastHelper.sendInform(context,"url",url);
}
});
3- in your fragment this use :
Receiver receiver;
boolean isReciverRegistered = false;
#Override
public void onResume() {
super.onResume();
if (receiver == null) {
receiver = new Receiver();
IntentFilter filter = new IntentFilter(BroadcastHelper.ACTION_NAME);
getActivity().registerReceiver(receiver, filter);
isReciverRegistered = true;
}
}
#Override
public void onDestroy() {
if (isReciverRegistered) {
if (receiver != null)
getActivity().unregisterReceiver(receiver);
}
super.onDestroy();
}
private class Receiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
Log.v("r", "receive " + arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME));
String methodName = arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME);
if (methodName != null && methodName.length() > 0) {
Log.v("receive", methodName);
switch (methodName) {
case "url":
/* call post method here */
default:
break;
}
}
}
}
UploadHelper Class :
public class UploadHelper {
/**
* Turn drawable resource into byte array.
*
* #param context parent context
* #param id drawable resource id
* #return byte array
*/
public static byte[] getFileDataFromDrawable(Context context, int id) {
Drawable drawable = ContextCompat.getDrawable(context, id);
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
/**
* Turn drawable into byte array.
*
* #return byte array
*/
public static byte[] getFileDataFromDrawable(Context context, Uri uri) {
// Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
InputStream iStream = context.getContentResolver().openInputStream(uri);
int bufferSize = 2048;
byte[] buffer = new byte[bufferSize];
// we need to know how may bytes were read to write them to the byteBuffer
int len = 0;
if (iStream != null) {
while ((len = iStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, len);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
}
Volley wasn't really meant for video uploading. It is better suited to large in number - small in size uploads/downloads. I would recommend using a different method to upload your video.
Volley is not suitable for large download or streaming operations,
since Volley holds all responses in memory during parsing. For large
download operations, consider using an alternative like
DownloadManager.*
Taken from https://developer.android.com/training/volley/

Gallery doesn't refresh using MediaScan

I have the following Java code which downloads an image from an URL.
I can see the image downloaded in the folder, but the image does not appear in gallery. Only if I restart phone, Samsung S7 with android 7, I can see images in gallery. What can I do to have the images in gallery in real time after I downloaded them?
public class DetailsImgActivity extends AppCompatActivity {
private static final String TAG = "DetailsImgActivity";
private ImageView imageViewPoze;
private Button buttonDownload;
private static final int PERMISSION_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details_img);
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
// image url stored in imageID
final String imageId = getIntent().getStringExtra("ImageId");
imageViewPoze = findViewById(R.id.imageViewPozeC);
Picasso.get().load(imageId).into(imageViewPoze);
buttonDownload = findViewById(R.id.btn_Download_Img);
buttonDownload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
downloadFile(imageId);
}
});
}
private void downloadFile(String url) {
Retrofit.Builder builder = new Retrofit.Builder().baseUrl("https://firebasestorage.blabla.com/");
Retrofit retrofit = builder.build();
FileDownloadClient fileDownloadClient = retrofit.create(FileDownloadClient.class);
Call<ResponseBody> call = fileDownloadClient.downloadFile(url);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
// if (response.isSuccess()) {
Log.d(TAG, "server contacted and has file");
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
boolean writtenToDisk = writeResponseBodyToDisk(response.body());
return null;
}
}.execute();
//after the image has been downloaded -refresh gallery
**Toast.makeText(getApplicationContext(), "File downloaded with success!", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File("file://"+ Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
}
else
{
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}**
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e(TAG, "error");
}
});
}
private boolean writeResponseBodyToDisk(ResponseBody body) {
try {
String folder_main = Constants.dirName;
File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), folder_main);
if (!f.exists()) {
f.mkdirs();
}
// todo change the file location/name according to your needs
File futureStudioIconFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM+"/"+ Constants.dirName)
+ File.separator + UUID.randomUUID()+".jpg");
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
long fileSize = body.contentLength();
long fileSizeDownloaded = 0;
inputStream = body.byteStream();
outputStream = new FileOutputStream(futureStudioIconFile);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
fileSizeDownloaded += read;
Log.d(TAG, "file download: " + fileSizeDownloaded + " of " + fileSize);
}
outputStream.flush();
return true;
} catch (IOException e) {
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
return false;
}
}
}
I used the follwing code, but If I don't reboot phone, I can't see the picture in gallery.
**Toast.makeText(getApplicationContext(), "File downloaded with success!", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File("file://"+ Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
}
else
{
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}**

XMLRPC Wordpress Image Upload - Uploads Empty Image?

I am trying to upload an image file to a Wordpress Site using XMLRPC.
I'm using org.apache.xmlrpc:xmlrpc-client to make the connection from Android, and I can successfully hit the website, and fire the upload, but the image file is empty on the site. I've sent through a base64 encoded string as the WP API states but I just can't get it to work?
Anyone know why?
This is my code:
public static void updatePhoto(final String status, final Context context, final String uri) {
websiteUrl = (String) loadPreference("wordpressUrl", context,String.class);
username = (String) loadPreference("wordpressUsername", context,String.class);
password = (String) loadPreference("wordpressPassword", context,String.class);
AsyncTask.execute(new Runnable() {
#Override
public void run() {
try {
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(new URL(websiteUrl+"/xmlrpc.php"));
XmlRpcClient rpcClient = new XmlRpcClient();
rpcClient.setConfig(config);
Uri realUri = getImageContentUri(context,Uri.parse(uri).getPath());
final InputStream imageStream = context.getContentResolver().openInputStream(realUri);
Bitmap originalBitmap = BitmapFactory.decodeStream(imageStream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
originalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] outputByteArray = baos.toByteArray();
String base64EncodedString = Base64.encodeToString(outputByteArray, Base64.DEFAULT);
Map content = new Hashtable();
content.put("name", status+".jpg");
content.put("type", "image/jpeg");
content.put("bits", base64EncodedString);
content.put("overwrite", false);
// Make the XMLRPC call.
Object result = rpcClient.execute("wp.uploadFile", new Object[]{
0,
username,
password,
content
});
// Print result - this is the new post's ID.
System.out.println(result);
} catch (final XmlRpcException e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
}
});
} catch (final Exception e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
});
}
public static Uri getImageContentUri(Context context, String absPath) {
Log.v(TAG, "getImageContentUri: " + absPath);
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
, new String[] { MediaStore.Images.Media._ID }
, MediaStore.Images.Media.DATA + "=? "
, new String[] { absPath }, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI , Integer.toString(id));
} else if (!absPath.isEmpty()) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, absPath);
return context.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} else {
return null;
}
}
private static String encodeImage(Bitmap bm)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
byte[] b = baos.toByteArray();
String encImage = Base64.encodeToString(b, Base64.NO_WRAP);
return encImage;
}

prevent image encoding in java

I have code to upload image and text to the server, but my code encodes the image and in the server the image should be decoded.
I want to prevent image encoding. I've tried some ways but they're not working.
I don't know how to do this. Please help me.
Here is my code:
public class Share_food extends Activity {
ProgressDialog prgDialog;
String encodedString;
RequestParams params = new RequestParams();
String imgPath, fileName;
Bitmap bitmap;
private static int RESULT_LOAD_IMG = 1;
EditText ti,desc;
TextView tv;
String url="http://example.com/index.php";
#SuppressLint("CutPasteId")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.share_food);
prgDialog = new ProgressDialog(this);
prgDialog.setCancelable(false);
ti= (EditText)findViewById(R.id.title);
desc=(EditText)findViewById(R.id.share_desc22);
//getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
//getActionBar().setIcon( new ColorDrawable(getResources().getColor(android.R.color.transparent)));
//getActionBar().setTitle("");
}
public void loadImagefromGallery(View view) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgPath = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgPath));
String fileNameSegments[] = imgPath.split("/");
fileName = fileNameSegments[fileNameSegments.length - 1];
params.put("filename", fileName);
} else {
Toast.makeText(this, "error",
Toast.LENGTH_LONG).show();
imgPath="2";
}
} catch (Exception e) {
Toast.makeText(this, "error...!", Toast.LENGTH_LONG)
.show();
}
}
public void uploadImage(View v) {
if (imgPath != null && !imgPath.isEmpty()) {
prgDialog.setMessage("process");
prgDialog.show();
encodeImagetoString();
} else {
prgDialog.setMessage("process");
prgDialog.show();
triggerImageUpload();
}
}
public void encodeImagetoString() {
new AsyncTask<Void, Void, String>() {
protected void onPreExecute() {
};
#Override
protected String doInBackground(Void... params) {
BitmapFactory.Options options = null;
options = new BitmapFactory.Options();
options.inSampleSize = 3;
bitmap = BitmapFactory.decodeFile(imgPath,
options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
byte[] byte_arr = stream.toByteArray();
encodedString = Base64.encodeToString(byte_arr, 0);
return "";
}
#Override
protected void onPostExecute(String msg) {
prgDialog.setMessage("upload");
params.put("title", ti.getText().toString().trim());
//desc
//params.put("desc",desc.getText().toString().trim());
params.put("image", encodedString);
triggerImageUpload();
}
}.execute(null, null, null);
}
public void triggerImageUpload() {
params.put("title", ti.getText().toString().trim());
//desc
//params.put("desc", desc.getText().toString().trim());
makeHTTPCall();
}
public void makeHTTPCall() {
prgDialog.setMessage("connecting");
AsyncHttpClient client = new AsyncHttpClient();
client.post(url,
params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
prgDialog.hide();
Toast.makeText(getApplicationContext(), "done",
Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(int statusCode, Throwable error,
String content) {
prgDialog.hide();
if (statusCode == 404) {
Toast.makeText(getApplicationContext(),
"error",
Toast.LENGTH_LONG).show();
}
else if (statusCode == 500) {
Toast.makeText(getApplicationContext(),
"error",
Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(
getApplicationContext(),
"error !!!"
+ statusCode, Toast.LENGTH_LONG)
.show();
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
if (prgDialog != null) {
prgDialog.dismiss();
}
}
}
you have to decode the string in receiving end and save the decoded one. post the code of receiving end too for more convenience.

Categories