getting captured photo didn't work - java

I want to let user capture image from camera and upload to server. So, I need an image file from captured photo.
I searched for many solutions but none of them worked.
I tried following:
Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (camera_intent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(camera_intent, 1);
}
in onActivityResult:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent dataIntent) {
super.onActivityResult(requestCode, resultCode, dataIntent);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 1) {
Bundle dataBundle = dataIntent.getExtras();
Bitmap imageBitmap = (Bitmap) dataBundle.get("data");
img_profile.setImageBitmap(imageBitmap); //getting thumbnail and setting to preview image
try{
Uri selectedImageUri = dataIntent.getData();
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(selectedImageUri, projection, null, null,null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String filePath = cursor.getString(column_index);
profilePicFile = new File(filePath);
cursor.close();
}
catch (Exception e){
e.printStackTrace();
}
but my I got nullPinterException saying that Uri is null. I tried almost all solutions on web but didn't work. Can anyone have any solution for this?

I had the same issue. I was able to solve this using FileObserver.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TAKE_PICTURE_REQUEST && resultCode == RESULT_OK) {
String thumbnailPath = data.getStringExtra(Intents.EXTRA_THUMBNAIL_FILE_PATH);
String picturePath = data.getStringExtra(Intents.EXTRA_PICTURE_FILE_PATH);
processPictureWhenReady(picturePath);
// TODO: Show the thumbnail to the user while the full picture is being
// processed.
}
super.onActivityResult(requestCode, resultCode, data);
}
private void processPictureWhenReady(final String picturePath) {
final File pictureFile = new File(picturePath);
if (pictureFile.exists()) {
// The picture is ready; process it.
} else {
// The file does not exist yet. Before starting the file observer, you
// can update your UI to let the user know that the application is
// waiting for the picture (for example, by displaying the thumbnail
// image and a progress indicator).
final File parentDirectory = pictureFile.getParentFile();
FileObserver observer = new FileObserver(parentDirectory.getPath(),
FileObserver.CLOSE_WRITE | FileObserver.MOVED_TO) {
// Protect against additional pending events after CLOSE_WRITE
// or MOVED_TO is handled.
private boolean isFileWritten;
#Override
public void onEvent(int event, String path) {
if (!isFileWritten) {
// For safety, make sure that the file that was created in
// the directory is actually the one that we're expecting.
File affectedFile = new File(parentDirectory, path);
isFileWritten = affectedFile.equals(pictureFile);
if (isFileWritten) {
stopWatching();
// Now that the file is ready, recursively call
// processPictureWhenReady again (on the UI thread).
runOnUiThread(new Runnable() {
#Override
public void run() {
processPictureWhenReady(picturePath);
}
});
}
}
}
};
observer.startWatching();
}
}
Here is the link that I refer to solve the issue. Its for Google glass but works fine on any Android device.

Related

Set two cropped image from camera separately in image view (Android Studio)

I am try to take two image from camera and crop image then show cropped image in two Imageview separately.
I have 2 Button to open camera one for capture first image then cropped to display it in Imageview and the second do the same thing.
My code in MainActivity
variable in calss
static int CAMERA_REQUEST_CODE = 228;
static int CAMERA_REQUEST_CODE1 = 229;
Uri pictureUri = null;
ImageView iv, iv1;
Button bt, bt1;
onCreate method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = findViewById(R.id.iv);
bt = findViewById(R.id.bt);
iv1 = findViewById(R.id.iv1);
bt1 = findViewById(R.id.bt1);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
invokeCamera();
}
});
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
invokeCamera1();
}
});
}
invokeCamera() and invokeCamera1() function
public void invokeCamera() {
// get a file reference
pictureUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName(), createImageFile()); // Make Uri file example file://storage/emulated/0/Pictures/Civil_ID20180924_180619.jpg
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Go to camera
// tell the camera where to save the image.
intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
// tell the camera to request WRITE permission.
intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
public void invokeCamera1() {
// get a file reference
pictureUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName(), createImageFile()); // Make Uri file example file://storage/emulated/0/Pictures/Civil_ID20180924_180619.jpg
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Go to camera
// tell the camera where to save the image.
intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
// tell the camera to request WRITE permission.
intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(intent, CAMERA_REQUEST_CODE1);
}
createImageFile() function
// To create image file in pictures directory
public File createImageFile() {
// the public picture director
File picturesDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); // To get pictures directory from android system
// timestamp makes unique name.
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String timestamp = sdf.format(new Date());
// put together the directory and the timestamp to make a unique image location.
File imageFile = new File(picturesDirectory, timestamp + ".jpg");
return imageFile;
}
onActivityResult function
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK) // resultCode: -1
{
if(requestCode == CAMERA_REQUEST_CODE ) // requestCode: 288
{
Uri picUri = pictureUri;
startCropImageActivity(picUri);
Toast.makeText(MainActivity.this, "Image 1 save",
Toast.LENGTH_SHORT).show();
}
if(requestCode == CAMERA_REQUEST_CODE1)
{
Uri picUri = pictureUri;
startCropImageActivity(picUri);
Toast.makeText(MainActivity.this, "Image 2 save",
Toast.LENGTH_SHORT).show();
}
}
if(requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK)
{
Croppedimage(result, iv); // my problem !
/*
* Here i want to use if or switch statement to can use iv1
for second camera button! HOW?
*
* example
*
* if(for first camera button)
* {
* Croppedimage(result, iv);
* }
*
* if(for second camera button)
* {
* Croppedimage(result, iv1);
* }
*
* */
}
else if(resultCode ==
CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE)
{
// if there is any error show it
Exception error = result.getError();
Toast.makeText(this, "" + error, Toast.LENGTH_LONG).show();
}
}
}
startCropImageActivity function
private void startCropImageActivity(Uri imageUri) {
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(true)
.start(this);
}
Croppedimage function
public void Croppedimage(CropImage.ActivityResult result,ImageView iv)
{
Uri resultUri = null; // get image uri
if (result != null) {
resultUri = result.getUri();
}
//set image to image view
iv.setImageURI(resultUri);
}
____________________________________________________________________________
The problem
The cropped image for second Button set in first Imageview.
Need to find way to reach to iv1 in onActivityResult for second camera Button.
Any suggestions?
Library use for crop image
THANKS.
Looking in the issues on the GitHub respository I found this one, that seems similar to yours, you can set a custom request code when starting the crop activity.
So you can start the activity with 2 different request codes and check which one has been used on onActivityResult
private static final RC_CROP = 100;
private static final RC_CROP1 = 200;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) // resultCode: -1
{
if (requestCode == CAMERA_REQUEST_CODE) // requestCode: 288
{
Uri picUri = pictureUri;
startCropImageActivity(picUri, RC_CROP);
Toast.makeText(MainActivity.this, "Image 1 save",
Toast.LENGTH_SHORT).show();
}
if (requestCode == CAMERA_REQUEST_CODE1) {
Uri picUri = pictureUri;
startCropImageActivity(picUri, RC_CROP1);
Toast.makeText(MainActivity.this, "Image 2 save",
Toast.LENGTH_SHORT).show();
}
if (requestCode == RC_CROP) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
//put image on first ImageView
}
if (requestCode == RC_CROP1) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
//put image on second ImageView
}
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
// if there is any error show it
Exception error = result.getError();
Toast.makeText(this, "" + error, Toast.LENGTH_LONG).show();
}
}
private void startCropImageActivity(Uri imageUri, int requestCode) {
Intent vCropIntent = CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(true)
.getIntent(this);
startActivityForResult(vCropIntent, requestCode)
}
I suggest also to use a switch statement when checking the requestCode

Save Image and Mp3 from Gallery to Internal Storage Directory Android

So, I am doing a University project whereby I am allowing the user to select an Image from camera/gallery and then also select an mp3. I would like to take these two selected files and save them into an internal storage directory with the same name(only the extension .mp3 / .jpg will differ)
I have managed to get the code to create the folder as well as get an image from the camera/gallery but I cant seem to work out how to save it to the internal storage directory or how to get an mp3 in the same way.
Code to create folder
try{ File folder = new File(Environment.getExternalStorageDirectory() + "/InkousticMedia");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
}catch (Exception e){
Log.e("MODEL", "ERROR: " + e.toString());
}
Code to get the image from MediaStore :
public class SaveTattooActivity extends AppCompatActivity {
public void getPhoto()
{
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,1);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == 1)
{
if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
getPhoto();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save_tattoo);
if(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}else
{
getPhoto();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && requestCode == RESULT_OK && data != null)
{
Uri selectedImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I have had a look at other similar questions on stack but they all differ so much and there is no concrete answer that I can seem to work out whereby I can save both the mp3 and image into the directory.
This is the code i used to save the image, check this github repository https://github.com/Rawkush/Status-Saver.
File f1,f2;
f1 = new File(uri.toString());
String fname = f1.getName();
f2 = new File(Environment.getExternalStorageDirectory()+"/YOUR_FOLDER/");
f2.mkdirs();
try {
FileUtils.copyFileToDirectory(f1,f2);
ContentValues values =new ContentValues();
values.put(MediaStore.Images.Media.DATE_TAKEN,System.currentTimeMillis());
values.put(MediaStore.Images.Media.MIME_TYPE,"image/jpeg");
values.put(MediaStore.MediaColumns.DATA,f2.toString()+"/"+fname);
getContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}finally {
Toast.makeText(getContext(),"Saved",Toast.LENGTH_LONG).show();
}

Picking Frames from a Video saved in my Gallery Android Studio

I am pretty new to android studio(and java) and i am attempting to make a video processing application. I want the program to upload a video from the users gallery, and then take a picture of the video every second and save it into an array. Logically the code I have written makes sense to me and there are no errors, but when I run the app on my Samsung tablet it crashes after taking the video. I think the setDataSource is unable to find the correct data source, but im not sure how to pass the data from the video along. Can anyone help?
Heres my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
savedimage = (ImageView) findViewById(R.id.imageView);
}
public void activity(View view) {
startActivityForResult(new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.INTERNAL_CONTENT_URI), GET_FROM_GALLERY);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
Uri videouri = data.getData();
retriever.setDataSource(String.valueOf(videouri));
String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
long timeInmillisec = Long.parseLong(time);
long seconds = timeInmillisec / 1000;
ArrayList<Bitmap> mylist = new ArrayList<Bitmap>();
for (int i = 0; i < seconds; i++) {
Bitmap bArray = retriever.getFrameAtTime(100000 * i, MediaMetadataRetriever.OPTION_CLOSEST);
mylist.add(bArray);
}
}
Since your videouri is a Uri, try calling void setDataSource (Context context, Uri uri) instead of void setDataSource (String path):
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check for resultCode & requestCode
if (resultCode == RESULT_OK) {
if (requestCode == GET_FROM_GALLERY) {
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
Uri videouri = data.getData();
// "videouri" is Uri, call setDataSource (Context context, Uri uri) instead
retriever.setDataSource(this, videouri);
.....
}
}

Uploading a File (Multipart/Form data) to Server Failed in Android using ion library

I am new in android ,and am trying to upload a file to server using ion library
ion library but the file crashes. with this error.
FATAL EXCEPTION: Thread-55725
Process: transitions.com.example.huzy_kamz.interview, PID: 4635
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:209)
at android.os.Handler.<init>(Handler.java:123)
at android.app.Dialog.<init>(Dialog.java:122)
at android.app.AlertDialog.<init>(AlertDialog.java:200)
at android.app.AlertDialog.<init>(AlertDialog.java:196)
at android.app.AlertDialog.<init>(AlertDialog.java:141)
at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
at transitions.com.example.huzy_kamz.interview.MainActivity.uploadFile(MainActivity.java:131)
at transitions.com.example.huzy_kamz.interview.MainActivity$2$1.run(MainActivity.java:66)
at java.lang.Thread.run(Thread.java:818)
This is how am using ion library to upload my file
public class MainActivity extends AppCompatActivity {
private static final int PICK_FILE_REQUEST = 1;
private static final String TAG = MainActivity.class.getSimpleName();
private String selectedFilePath;
private String SERVER_URL = "http://192.168.43.104:8093/PoliceApp/FileUpload.aspx";
ImageView ivAttachment;
private String UPLOAD_URL ="http://192.168.43.104:8093/PoliceApp/ImageUpload.aspx";
ProgressDialog dialog;
private ImageView imageView;
private EditText firstname_edt,lastname_edt,email_edt,jobtitle_edt,source_edt;
private TextView directory_txt;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView= (ImageView)findViewById(R.id.imageView);
firstname_edt=(EditText)findViewById(R.id.firstname_edt);
lastname_edt=(EditText)findViewById(R.id.lastname_edt);
email_edt=(EditText)findViewById(R.id.email_edt);
jobtitle_edt=(EditText)findViewById(R.id.jobtitle_edt);
source_edt=(EditText)findViewById(R.id.source_edt);
button=(Button)findViewById(R.id.button);
directory_txt=(TextView)findViewById(R.id.directory_txt);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFileChooser();
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(selectedFilePath != null){
dialog = ProgressDialog.show(MainActivity.this,"","Uploading File...",true);
new Thread(new Runnable() {
#Override
public void run() {
//creating new thread to handle Http Operations
uploadFile(selectedFilePath);
// OnSendFileInfo();
}
}).start();
}else{
Toast.makeText(MainActivity.this,"Please choose a File First",Toast.LENGTH_SHORT).show();
}
}
});
}
// Gallery pick
private void showFileChooser() {
Intent intent = new Intent();
//sets the select file to all types of files
intent.setType("*/*");
//allows to select data and return it
intent.setAction(Intent.ACTION_GET_CONTENT);
//starts new activity to select file and return data
startActivityForResult(Intent.createChooser(intent,"Choose File to Upload.."),PICK_FILE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK){
if(requestCode == PICK_FILE_REQUEST){
if(data == null){
//no data present
return;
}
Uri selectedFileUri = data.getData();
selectedFilePath = FilePath.getPath(this,selectedFileUri);
Log.i(TAG,"Selected File Path:" + selectedFilePath);
if(selectedFilePath != null && !selectedFilePath.equals("")){
directory_txt.setText(selectedFilePath);
}else{
Toast.makeText(this,"Cannot upload file to server",Toast.LENGTH_SHORT).show();
}
}
}
}
public void uploadFile(final String selectedFilePath){
final ProgressDialog pd;
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Uploading File...");
pd.setCancelable(false);
pd.show();
final String url_ = "";
Ion.with(MainActivity.this)
.load(SERVER_URL)
.uploadProgressDialog(pd)
.setMultipartParameter("uploaded_file",selectedFilePath)
.setMultipartFile("archive", "application/zip", new File(selectedFilePath))
.asString()
.setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
Toast.makeText(MainActivity.this," "+result,Toast.LENGTH_LONG).show();
pd.dismiss();
}
});
}
}
My Method Contain ion library to Upload a PDF file .
public void uploadFile(final String selectedFilePath){
final ProgressDialog pd;
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Uploading ...");
pd.setCancelable(false);
pd.show();
final String url_ = "";
//File file = new File(this.getFilesDir().getAbsolutePath() + "/thesubdirectory/the.zip");
File f = new File(getApplicationContext().getFilesDir().getAbsolutePath()+selectedFilePath);
try {
RandomAccessFile rf = new RandomAccessFile(f, "rw");
rf.setLength(1024 * 1024 * 2);
} catch (Exception e) {
System.err.println(e);
}
File echoedFile = getFileStreamPath("echo");
Ion.with(MainActivity.this)
.load(SERVER_URL)
.uploadProgressDialog(pd)
.setMultipartFile("uploaded_file",f)
.write(echoedFile)
.setCallback(new FutureCallback<File>() {
#Override
public void onCompleted(Exception e, File result) {
try {
Toast.makeText(MainActivity.this, " " + result, Toast.LENGTH_LONG).show();
System.out.println("Error " + result);
pd.dismiss();
} catch (Exception e1) {
System.out.println("Error " + e1);
}
pd.dismiss();
}
});
}
I don't where am wrong please i need your help, where am i wrong.
My back end is working fine , but the problem is in the uploading process.
This is my C# Api to locate the File in a specified folder.
public void FileSave(HttpPostedFile file)
{
try
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/FileStorage"), fileName);
file.SaveAs(path);
}
Response.Write("Upload successfull");
}
catch
{
Response.Write("An Error Ocurred");
}
}
Remove Thread from calling chain as Ion manages that for you and your exception is not related to Ion FYI.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(selectedFilePath != null){
dialog = ProgressDialog.show(MainActivity.this,"","Uploading File...",true);
uploadFile(selectedFilePath);
// OnSendFileInfo();
}else{
Toast.makeText(MainActivity.this,"Please choose a File First",Toast.LENGTH_SHORT).show();
}
}
});
You can not use a View in Non Ui thread . So as i am seeing that you are creating a progress dialog inside your upload method which is being called for a thread .That code should be in Main thread only.
Well i have found out a simple way of uploading or posting multipart/form-data with an upload progress bar. may be this could help.
Suppose you server is waiting for the following data :
1.File(PDF,Image,Audio,Video etc.).
2.Name
3.Email
4.Address.
and you want to upload that information once in a URL be it an Absolute URL or a Relative URL, ion library is easy , precise, efficient and much better in this.
STEP 1:
declare your URI
private Uri filePath;
STEP 2:
then Pick the file from your gallery , here it's your choice you identify any kind of files you want a user to view, me here i have identified a PDF file.
on this line intent.setType("application/pdf");
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Pdf"), PICK_PDF_REQUEST);
}
//handling the image chooser activity result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_PDF_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
Toast.makeText(getApplicationContext(), "" + filePath, Toast.LENGTH_LONG).show();
}
}
then you can call showFileChooser() in the Button for a click to access your gallery.
STEP 3:
a) Make a method Upload() containing ion library to start the job. If you see in this method , i first declared the file,name, email,address , for file it gets the URI data of a selected file or the path file , then name, email,address, it gets the data from EditText , you have to declare EditText to get the data.
b) Then identify the URL you want to use in Posting mine is url_. but make sure you include POST, in the load section .load("POST",url_).
c) Then you set the file by using .setMultipartFile("File", file) and the rest of the parameters by setting MultipartParameter .setMultipartParameter("Name", name) and so on.
public void Upload() {
String file= FilePath.getPath(this, filePath);
final String name = name_edt.getText().toString();
final String email = email_edt.getText().toString();
final String address = address_edt.getText().toString();
final ProgressDialog pd;
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Logging in...");
pd.setCancelable(false);
pd.show();
final String url_ = "xxxxxxxxxxxxxxx";
final File file = new File(Uri.parse(path).toString());
Ion.with(MainActivity.this)
.load("POST",url_)
.progressDialog(pd)
.setMultipartFile("file", file)
.setMultipartParameter("Name", name)
.setMultipartParameter("Email", email)
.setMultipartParameter("Address.", address)
.asString()
.setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
// Toast.makeText(getApplicationContext(),""+file,Toast.LENGTH_LONG).show();
System.out.println("Error " + e);
// Toast.makeText(getApplicationContext(), "Exception : " + e, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(),""+e,Toast.LENGTH_LONG).show();
pd.dismiss();
}
});
}
Then you are good to go , according to your C# API , the file will be able to save in the Folder. Even others use Php or any other language you can create your own Api to save a file in your server folder
Hope it works well.

Upload image from entire phone

I have created an activity that upon button click user are able to upload a picture from their device gallery, which would get cast to an imageview. The problem is that it is only able to retrieve image from device gallery, not from phone camera gallery, or from phone google drive folder. I would want that its able to upload any picture from their phone, regardless of the source.
Below is the code:
Button buttonLoadImage = (Button) findViewById(R.id.btnPictureSelect);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && 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]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
private byte[] readInFile(String path) throws IOException {
// TODO Auto-generated method stub
byte[] data = null;
File file = new File(path);
InputStream input_stream = new BufferedInputStream(new FileInputStream(
file));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
data = new byte[16384]; // 16K
int bytes_read;
while ((bytes_read = input_stream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, bytes_read);
}
input_stream.close();
return buffer.toByteArray();
}
Any help would be greatly appreciated.
Update:
private static final int READ_REQUEST_CODE = 42;
in the code
Button buttonLoadImage = (Button) findViewById(R.id.btnPictureSelect);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent imageIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
imageIntent.addCategory(Intent.CATEGORY_OPENABLE);
imageIntent.setType("image/*");
imageIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(imageIntent , READ_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri uri = null;
if (data != null) {
uri = data.getData();
Log.i(TAG, "Uri: " + uri.toString());
showImage(uri);
}
}
}
private void showImage(Uri uri) {
// TODO Auto-generated method stub
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageUri(Uri.parse(new File("path_to_your_image".toString()));
}
error:
The method parse(String) in the type Uri is not applicable for the arguments (File)
in line
imageView.setImageUri(Uri.parse(new File("path_to_your_image".toString()));
Update 2:
private void showImage(Uri uri) {
// TODO Auto-generated method stub
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageUri(Uri.fromFile(new File("/sdcard/myimage.jpg")));
error:
The method setImageUri(Uri) is undefined for the type ImageView
It would be better to use Intent to search the image type files available in your device.
Intent imageIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
imageIntent.addCategory(Intent.CATEGORY_OPENABLE);
imageIntent.setType("image/*");
imageIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(imageIntent , READ_REQUEST_CODE); // set READ_REQUEST_CODE to 42 in your class
Now, process your results in the onActivityResult() method.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri uri = null;
if (data != null) {
uri = data.getData();
Log.i(TAG, "Uri: " + uri.toString());
showImage(uri);
}
}

Categories