Android having problems while uploading Images using Retrofit multipart? - java

I'm getting the following error while trying to upload an Image to a server using retrofit, the api receives a header authorization token, _method = "put" and image = "imageName.jpg" as parameters, everything else is optional, any help would be appreciated.
java.io.FileNotFoundException: /storage/emulated/0/Download/space-wallpaper-21.jpg: open failed: EACCES (Permission denied)
userImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galleryIntent.setType("*/*");
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imageDecodableString = cursor.getString(columnIndex);
cursor.close();
StringBuilder stringBuilder = new StringBuilder(AUTHORIZATION);
sharedPreferences = this.getSharedPreferences(getResources().getString(R.string.token), 0);
stringBuilder.append(sharedPreferences.getString(getResources().getString(R.string.token), ""));
methodMap.put("_method", "PUT");
File file = new File(imageDecodableString);
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestBody);
//RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "image");
Call<UserInfo> uploadImage = new RestClient(CONSTS.BASE_URL_ADDRESS_ACCOUNT_CREATION).getUserSignUpClient()
.postImage(stringBuilder.toString(), methodMap, body);
uploadImage.enqueue(new Callback<UserInfo>() {
#Override
public void onResponse(Call<UserInfo> call, Response<UserInfo> response) {
if (response.isSuccessful()) {
}
}
#Override
public void onFailure(Call<UserInfo> call, Throwable t) {
Toast.makeText(DetailActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
Interface:
public interface UserSignUpClient {
#POST("account")
Call<AuthenticationAccountCreationResponse> createAccount(#Body UserSignUp userSignUp);
#Multipart
#POST("account")
Call<UserInfo> postImage(#Header("Authorization") String headerValue, #PartMap Map<String, String> map, #Part MultipartBody.Part image);
}
Retrofit Builder Class:
public class RestClient {
private UserSignInClient userSignInClient;
private UserSignUpClient userSignUpClient;
private UserInfoClient userInfoClient;
private UserImageUploadClient userImageUploadClient;
public RestClient(String baseUrlLink){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrlLink)
.addConverterFactory(GsonConverterFactory.create()).build();
if (baseUrlLink.equals(CONSTS.BASE_URL_ADDRESS_TOKEN)){
userSignInClient = retrofit.create(UserSignInClient.class);
} else if (baseUrlLink.equals(CONSTS.BASE_URL_ADDRESS_ACCOUNT_CREATION)) {
userSignUpClient = retrofit.create(UserSignUpClient.class);
} else if (baseUrlLink.equals(CONSTS.BASE_URL_ADDRESS_USER_INFO)){
userInfoClient = retrofit.create(UserInfoClient.class);
}
}
public UserSignInClient getUserSignInClient() {
return userSignInClient;
}
public UserSignUpClient getUserSignUpClient() {
return userSignUpClient;
}
public UserInfoClient getUserInfoClient() {
return userInfoClient;
}
}

For Below Android 6.0 Marshmallow :
Add Permission in Manifest :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
For Marshmallow and Above Device's:
public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback{
private static final int REQUEST_WRITE_PERMISSION = 786;
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == REQUEST_WRITE_PERMISSION && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openFilePicker();//do your job
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestPermission();
}
private void requestPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_PERMISSION);
} else {
openFilePicker();//do your job
}
}
}
For more info see below link's
Android 6.0 Marshmallow. Cannot write to SD Card
Read and Write permission for storage and gallery usage for marshmallow
Note: Do not forget to add permission in manifest file

Add this
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
inside the manifest tag of your manifest file.Makes sure its outside the application tag however.

Related

How do I store downloadUrl of multiple images to the Firebase Firestore ? Unable to create and store inside multiple fields inside Firestore document

Here's what I have been able to get so far. After selecting the images
selectImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mUploadTask != null && mUploadTask.isInProgress()){
Toast.makeText(MainActivity.this, "Upload In Progress", Toast.LENGTH_SHORT).show();
}
else {
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), RESULT_LOAD_IMAGE);
}
}
});
Inside the OnActivityResult, I am uploading my selected Images to the Firebase Storage and at the same time I want to store my download Urls of those multiple images to the Firebase Firestore
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String fileName;
final String[] downloadUrl = new String[1];
if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK){
if(data.getClipData() != null){
int totalItemsSelected = data.getClipData().getItemCount();
for(int i =0;i<totalItemsSelected;i++){
Uri fileUri = data.getClipData().getItemAt(i).getUri();
fileName = getFileName(fileUri);
fileNameList.add(fileName);
fileDoneList.add("uploading");
uploadListAdapter.notifyDataSetChanged();
final StorageReference fileToUpload = storageReference.child("Images").child(fileName);
final int finalI = i;
final int totalCount = totalItemsSelected;
mUploadTask = fileToUpload.putFile(fileUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileToUpload.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String url = String.valueOf(uri);
storeLink(url,totalCount);//Method To Store the Url
}
});
// Toast.makeText(add_for_sale.this, "Uploading works", Toast.LENGTH_SHORT).show();
fileDoneList.remove(finalI);
fileDoneList.add(finalI,"done");
uploadListAdapter.notifyDataSetChanged();
}
});
// ImageUploadInfo imageUploadInfo = new ImageUploadInfo(downloadUrl[0],fileName);
}
Toast.makeText(this, "Upload in Progress", Toast.LENGTH_SHORT).show();
}
else if(data.getData() != null){
Toast.makeText(this, "Selected Single", Toast.LENGTH_SHORT).show();
}
}
}
In the method storeLink(url,totalCount), I am creating a map object to create field "imageUrl" inside the document,where "29t0Boxm0fa8UNkomuo5xPLwkx13" is a user id.
private void storeLink(final String url,final int totalCount) {
FirebaseFirestore storeUrl = FirebaseFirestore.getInstance();
Toast.makeText(MainActivity.this, url, Toast.LENGTH_LONG).show();
for (int i=0;i<totalCount;i++) {
final Map<String, Object> image = new HashMap<>();
image.put("imageUrl"+i, url);
DocumentReference documentReference = storeUrl.collection("users").document("29t0Boxm0fa8UNkomuo5xPLwkx13");
documentReference.set(image).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "" +
"OnSuccess : Image Link Saved ");
// startActivity(new Intent(Register.this,LoginActivity.class));
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "OnFailure : " + e.toString());
}
});
}
}
Storage Rules
rules_version = '2'
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if true;
}
}
Firestore Rules
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
Make sure you have made final to Map<String,Object> user = new HashMap<>();
And add user.put("key","value") inside the loop.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final DocumentReference documentReference = db.collection("users").document("multi_image");
final Map<String, Object> user = new HashMap<>();
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK) {
if (data.getClipData() != null) {
final int totalItemsSelected = data.getClipData().getItemCount();
for (int i = 0; i < totalItemsSelected; i++) {
Uri fileUri = data.getClipData().getItemAt(i).getUri();
final int x = i;
final StorageReference fileToUpload = mStorageRef.child("Images").child("" + x);
fileToUpload.putFile(fileUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> DownloadURL = taskSnapshot.getStorage().getDownloadUrl();
DownloadURL.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
user.put("image_" + x, uri.toString());
Log.v("users", "" + user);
documentReference.update(user)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.v("task", "Success");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.v("failed", "" + e);
}
});
}
});
}
});
}
Toast.makeText(this, "Upload in Progress", Toast.LENGTH_SHORT).show();
} else if (data.getData() != null) {
Toast.makeText(this, "Selected Single", Toast.LENGTH_SHORT).show();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
Firebase Storage https://i.stack.imgur.com/HeYvh.png
Firebase Database https://i.stack.imgur.com/3t2aN.png
Here's what worked out for me finally :
Create an ArrayList variable globally
ArrayList<String> imageList;
Then initialize this ArrayList inside the
onActivityResult as imageList = new ArrayList<>(totalItemsSelected); as mentioned inside the code below
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String fileName;
if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK){
if(data.getClipData() != null){
progressBar.setVisibility(View.VISIBLE);
final int totalItemsSelected = data.getClipData().getItemCount();
count = totalItemsSelected;
imageList = new ArrayList<>(totalItemsSelected);
StorageReference ImageFolder = FirebaseStorage.getInstance().getReference().child("ImageFolder");
for(int i =0;i<totalItemsSelected;i++){
Uri fileUri = data.getClipData().getItemAt(i).getUri();
fileName = getFileName(fileUri);
fileNameList.add(fileName);
fileDoneList.add("uploading");
uploadListAdapter.notifyDataSetChanged();
final StorageReference fileToUpload = ImageFolder.child(fileName);
final int finalI = i;
mUploadTask = fileToUpload.putFile(fileUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressBar.setVisibility(View.INVISIBLE);
fileToUpload.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String url = String.valueOf(uri);
imageList.add(url);
// Toast.makeText(add_for_sale.this, imageList.get(finalI), Toast.LENGTH_SHORT).show();
Log.i(TAG,"Added To List");
}
});
fileDoneList.remove(finalI);
fileDoneList.add(finalI,"done");
uploadListAdapter.notifyDataSetChanged();
}
});
}
Toast.makeText(this, "Upload in Progress", Toast.LENGTH_SHORT).show();
}
else if(data.getData() != null){
Toast.makeText(this, "Select Two or More Images", Toast.LENGTH_SHORT).show();
}
}
}
Now to Save the Url Links to the Firebase Firestore Add the links to the ArrayList as imageList.add(url;)
and upload this list imageList to the FireStore as
Map<String,Object> imageUrl = new HashMap<>();
imageUrl.put("ImageUrl", imageList);
String userId;
userId = firebaseUser.getUid();
firebaseFirestore.collection("ImageDetails").document(userId)
.set(imageUrl,SetOptions.merge());
This will create an array of ImageUrl inside your firestore document

Images Not Selectable in Photo Gallery

I have recently made it so users can choose an image from their photo gallery or downloads and upload it to Firebase Storage and use the image as their profile picture.
The issue is whenever a user goes into their gallery, all the photos are greyed out so they cannot select them to upload. I am assuming this is an issue with permissions, but I believe I have all the correct permissions in place to avoid this issue. This is the code being used to open the gallery, choose a photo, and upload a photo to the Firebase Storage
public class AccountSettings extends AppCompatActivity {
StorageReference storageReference;
private static final int IMAGE_REQUEST = 1;
private StorageTask uploadTask;
private Uri profileImage;
private void openImage() {
Intent intent = new Intent();
intent.setType("image/");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, IMAGE_REQUEST);
}
private String getFileExtension(Uri uri) {
ContentResolver contentResolver = AccountSettings.this.getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getMimeTypeFromExtension(contentResolver.getType(uri));
}
private void uploadImage() {
final ProgressDialog pd = new ProgressDialog(AccountSettings.this);
pd.setMessage("Uploading");
pd.show();
if (profileImage != null) {
final StorageReference fileReference = storageReference.child(System.currentTimeMillis() + "." + getFileExtension(profileImage));
uploadTask = fileReference.putFile(profileImage);
uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
return fileReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
String mUri = downloadUri.toString();
HashMap<String, Object> map = new HashMap<>();
map.put("imageURL", mUri);
HomePage.myRef.updateChildren(map);
pd.dismiss();
} else {
Toast.makeText(AccountSettings.this, "FAILED!!", Toast.LENGTH_SHORT).show();
pd.dismiss();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(AccountSettings.this, e.getMessage(), Toast.LENGTH_SHORT).show();
pd.dismiss();
}
});
} else {
Toast.makeText(AccountSettings.this, "No image selected", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
profileImage = data.getData();
if (uploadTask != null && uploadTask.isInProgress()) {
Toast.makeText(AccountSettings.this, "Upload in progress", Toast.LENGTH_SHORT).show();
} else {
uploadImage();
}
}
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
And these are the permissions I have in my Manifest to allow users to choose images - I believe the problem lies here but I am not positive
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I do not know why the images are not selectable

Getting a Unexpected JDWP Error: 103 while trying to upload an image using retrofit to an api server android?

I'm getting the following 103 error message while trying to upload an image on the api server using retrofit multipart, the api receives an api token, "_method":"PUT" and image url as parameters, on response receives the complete JSON but with the previous or default image link, the current selected image does not upload, everything else is optional, any help would be appreciated, code is listed below thanks.
Also main method is POST but "_method":"PUT" parameter lets you upload the image, without _method it becomes a POST message and every other parameter than becomes compulsory, please check the image.
com.sun.jdi.InternalException: Unexpected JDWP Error: 103
Interface:
public interface UserSignUpClient {
#POST("account")
Call<AuthenticationAccountCreationResponse> createAccount(#Body UserSignUp userSignUp);
#Multipart
#PUT("account")
Call<UserInfo> postImage(#Header("Authorization") String headerValue, #PartMap Map<String, String> map, #PartMap Map<String, File> imageMap, #Part MultipartBody.Part image);
#FormUrlEncoded
#POST("account")
Call<UserInfo> updateUser(#Header("Authorization") String headerValue, #FieldMap Map<String, String> map);
}
Retrofit builder class:
public class RestClient {
private UserSignInClient userSignInClient;
private UserSignUpClient userSignUpClient;
private UserInfoClient userInfoClient;
public RestClient(String baseUrlLink){
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrlLink)
.addConverterFactory(GsonConverterFactory.create(gson)).build();
if (baseUrlLink.equals(CONSTS.BASE_URL_ADDRESS_TOKEN)){
userSignInClient = retrofit.create(UserSignInClient.class);
} else if (baseUrlLink.equals(CONSTS.BASE_URL_ADDRESS_ACCOUNT_CREATION)) {
userSignUpClient = retrofit.create(UserSignUpClient.class);
} else if (baseUrlLink.equals(CONSTS.BASE_URL_ADDRESS_USER_INFO)){
userInfoClient = retrofit.create(UserInfoClient.class);
}
}
public UserSignInClient getUserSignInClient() {
return userSignInClient;
}
public UserSignUpClient getUserSignUpClient() {
return userSignUpClient;
}
public UserInfoClient getUserInfoClient() {
return userInfoClient;
}
}
Main Class:
userImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galleryIntent.setType("*/*");
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
Uri selectedImageUri = data.getData();
String filePath = FileUtils.getPath(this, selectedImageUri);
file = new File(filePath);
image_name = file.getName();
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
}
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
StringBuilder stringBuilder = new StringBuilder(AUTHORIZATION);
sharedPreferences = this.getSharedPreferences(getResources().getString(R.string.token), 0);
stringBuilder.append(sharedPreferences.getString(getResources().getString(R.string.token), ""));
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestBody);
UserUpdate userUpdate = new UserUpdate(file);
methodMap.put("_method","PUT");
imageMap.put("image", file);
Call<UserInfo> uploadImage = new RestClient(CONSTS.BASE_URL_ADDRESS_ACCOUNT_CREATION).getUserSignUpClient()
.postImage(stringBuilder.toString(), methodMap, imageMap, body);
uploadImage.enqueue(new Callback<UserInfo>() {
#Override
public void onResponse(Call<UserInfo> call, Response<UserInfo> response) {
if (response.isSuccessful()) {
Picasso.with(DetailActivity.this).load("http://ec2-35-161-195-128.us-west-2.compute.amazonaws.com/" + response.body().getImage()).into(userImage);
}
}
#Override
public void onFailure(Call<UserInfo> call, Throwable t) {
Toast.makeText(DetailActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
postman api image = https://i.imgur.com/AoCFZI6.png
I think your problem is you forgot to add a call adapter to the retrofit object. Within your RestClient class you must put something like this:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrlLink)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
Also you need to add this dependency inside build.gradle:
compile "com.squareup.retrofit2:adapter-rxjava2:2.3.0"
I hope it helps.
Cheers.
I updated the Retrofit dependancy to '2.4.0' and it solved the problem

Retrofit-IllegalArgumentException: unexpected url

I want to upload a video file (chosen from gallery) to a server using Retrofit. But it doesn't work and throws the exception "java.lang.IllegalArgumentException: unexpected url: 192.168.1.7". My code is presented below.
PostFile.java:
public final class PostFile {
public static final MediaType MEDIA_TYPE_MARKDOWN
= MediaType.parse("vide/mp4");
private final OkHttpClient client = new OkHttpClient();
public void run(String path) throws Exception {
File file = new File(path);
Request request = new Request.Builder()
.url("192.168.1.7/")
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
}
PostFile:
public class MainActivity extends Activity {
private static int RESULT_LOAD_IMG = 1;
String decodableString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void loadImagefromGallery(View view) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedVideo = data.getData();
String[] filePathColumn = { MediaStore.Video.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedVideo,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
decodableString = cursor.getString(columnIndex);
cursor.close();
new PostFile().run(decodableString);
Log.i("mohsen","done");
} else {
Toast.makeText(this, "You haven't picked any video",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
}
Wampserver is running Apache Server 2.4.4 on my computer.
Please note that I have no idea whether this code is sound or not, and I'm just trying to make it work almost blindly.
Try change
.url("192.168.1.7/")
to
.url("http://192.168.1.7")
modify your url to http://192.168.1.7. It should works perfectly.

libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)

I want to pick a video file from gallery (first part of my code) and upload it to a server using Retrofit-neglect it for this question please. So, I want to pass a File from the first part to the second one but it gives me the error mentioned in the title.
MainActivity:
public class MainActivity extends Activity
{
private static int RESULT_LOAD_VIDEO = 1;
String decodableString;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btn_load = (Button) findViewById(R.id.buttonLoadVideo);
btn_load.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
loadVideoFromGallery(btn_load);
}
});
}
/*
* PICK THE VIDEO AND EXTRACT ITS ADDRESS
*/
public void loadVideoFromGallery(View view)
{
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_VIDEO);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
try {
// When a video is picked
if (requestCode == RESULT_LOAD_VIDEO && resultCode == RESULT_OK
&& null != data)
{
// Get the video from data
Uri selectedVideo = data.getData();
String[] filePathColumn = { MediaStore.Video.Media.DATA };
Cursor cursor = getContentResolver().query(selectedVideo,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
decodableString = cursor.getString(columnIndex);
Log.i("mok","ds: " + decodableString);//ds: /storage/extSdCard/DCIM/Camera/20151112_142950.mp4
Log.i("mok","svp: " + selectedVideo.getPath());//svp: /external/video/media/253
Log.i("mok","fpc0: " + filePathColumn[0]);//fpc0: _data
cursor.close();
File file = new File(selectedVideo.getPath());
upload(file);
} else
{
Toast.makeText(this, "You haven't picked any video",
Toast.LENGTH_LONG).show();
}
} catch (Exception e)
{
e.printStackTrace();
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
/*
* UPLOAD THE SELECTED VIDEO TO THE SRVER
*/
public void upload(File file)
{
final String BASE_URL = "http://192.168.1.7/";
Retrofit retrofit = new Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
UploadApiService service = retrofit.create(UploadApiService.class);
MediaType MEDIA_TYPE = MediaType.parse("video/mp4");
RequestBody requestBody = RequestBody.create(MEDIA_TYPE, file);
Call<ResponseBody> call = service.uploadVideo("desc", requestBody);
call.enqueue(new Callback<ResponseBody>(){
#Override
public void onResponse(Response<ResponseBody> response, Retrofit retrofit)
{
// TODO Auto-generated method stub
if (response.isSuccess())
{
Log.i("mok","S");
ResponseBody rb = response.body();
}
else
{
Log.i("mok","F");
com.squareup.okhttp.ResponseBody rb = response.errorBody();
}
}
#Override
public void onFailure(Throwable t)
{
t.printStackTrace();
Log.i("mok",t.getCause()+"");
Log.i("mok","T");
finish();
}
});
}
}
Just I had to use File file = new File(decodableString). The error is gone (the question answered) so I posted this answer, but the solution for uploading the file is not working properly (that's another issue).

Categories

Resources