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.
Related
I wrote a program where a user can click a TextView (editPhoto) and select an image (profile picture) and display on the profile and also save it on my database with the rest of the profile details, but as soon as I leave the page the picture disappears from the CircleImageView although it's still saved on my database. I am able to save the rest of the users information on the profile like name, username, email etc using .setText() so how can I do the same with the CircleImageView for the profile picture? Thanks in advance
CODE:
private TextView editPhoto;
CircleImageView profilePic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
profilePic = findViewById(R.id.profilepic);
editPhoto = findViewById(R.id.txtEditPP);
editPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chooseFile();
}
});
}
private void chooseFile(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Choose Photo"),1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null){
Uri filepath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filepath);
profilePic.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
UploadPicture(getId, getStringImage(bitmap));
}
}
//UPLOAD PROFILE PICTURE
private void UploadPicture(final String id, final String photo) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_UPLOAD, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i(TAG, response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if (success.equals("1")){
Toast.makeText(EditProfile.this, "Photo Uploaded", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(EditProfile.this, "Error Uploading Image!", Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(EditProfile.this, "Error Uploading Image!", Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("ID", id);
params.put("photo", photo);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public String getStringImage(Bitmap bitmap){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] imageByteArr = byteArrayOutputStream.toByteArray();
String encodedImage = Base64.encodeToString(imageByteArr, Base64.DEFAULT);
return encodedImage;
}
In onResume can you reload imageView using bitmap object?
Also make bitmap object as class variable reloading image will work for you in this case.
My requirement is the end-user must be able to upload files into the application from internal or external storage and finally display the name of the file in the page.
Actual result: Now I've fetched the file name from the storage and displayed the name in my page.
Expected Result: The end user must be able to load image or video files from external or internal storage to the application and finally display their name in the page.
But don't have any idea about how to load read the file from storage and store it in a arrayList.
Code for fetching the file name
public class ServiceDetails extends AppCompatActivity {
private Button next, attachment_one;
private ImageButton attach_file;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enter_details);
next = findViewById(R.id.submit);
attachment_one = findViewById(R.id.attachmentOne);
attach_file = findViewById(R.id.attachFile);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ServiceDetails.this, ServiceAddress.class);
startActivity(intent);
}
});
attach_file.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.M &&
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 10001);
}
new MaterialFilePicker()
.withActivity(ServiceDetails.this)
.withRequestCode(1)
.withFilter(Pattern.compile(".*\\.(mkv|wmv|avi|mpeg|swf|mov|mp4|jpg|jpeg)$"))
.withHiddenFiles(true) // Show hidden files and folders
.start();
}
});
attachment_one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
attachment_one.setVisibility(View.INVISIBLE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
String file_path = data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH);
String file_array[] = file_path.split("/");
String file_name = file_array[file_array.length - 1];
// Do anything with file
if(attachment_one.getText().toString().isEmpty()) {
attachment_one.setVisibility(View.VISIBLE);
attachment_one.setText(file_name);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 10001: {
if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(ServiceDetails.this, "Permission granted", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(ServiceDetails.this, "Permission not granted", Toast.LENGTH_LONG).show();
finish();
}
}
}
}
}
I'm new to android and kindly help me providing solution for this answer. Million thanks in advance!
Image showing file attachment option
As you are willing to load the title of video/images, and other file related information from the External Storage. You have to use this code and also make sure don't forget to create a Arraylist with model(required to extract information and find to the listview).
//ContentResolver and contentProvider as well as cursor
String[] projection = new String[]{
MediaStore.Video.Media._ID,
MediaStore.Video.Media.TITLE,
MediaStore.Video.Media.SIZE,
MediaStore.Video.Media.DATE_MODIFIED
};
String selection = null;
String[] selectionargs = null;
String orderBy = MediaStore.Video.Media.DISPLAY_NAME + " Desc";
Uri content_uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
Cursor cursor = getContentResolver().query(content_uri, projection, selection, selectionargs, orderBy);
if (cursor != null) {
cursor.moveToPosition(0);
}
while (true) {
long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID));
Uri VideoUri = ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id);
Log.d("uri", "onCreate: video path " + VideoUri);
String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE));
float size = cursor.getFloat(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));
// loading a thumbnail from the content resolver
// Load thumbnail of a specific media item.
Bitmap thumbnail = null;
try {
thumbnail = getApplicationContext().getContentResolver().loadThumbnail(VideoUri, new Size(200, 200), null);
Log.d("thumbnail", "onCreate: Lodaing a thumbnail");
} catch (IOException e) {
Log.d("thumbnail", "onCreate: Showing Error on thumbnail");
e.printStackTrace();
}
videolist.add(new Video(thumbnail, VideoUri, title, size));
if (!cursor.isLast()) {
cursor.moveToNext();
} else {
Log.d("lastItem", "onCreate: last uri is encountered");
break;
}
}
cursor.close();
Hello There I am working on Next Cloud Api, and I am trying to upload an Image from my device as:
uploadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFileChooser();
}
});
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
and the on activity result is as:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
try {
// Get the Uri of the selected file
Uri uri = data.getData();
// Get the path
String path = getPath(MainActivity.this, uri);
File fi = new File(path);
//set the image to image view
iv.setImageURI(Uri.fromFile(fi));
Date lastModDate = new Date(fi.lastModified());
startUpload(fi, "/testfolder", getMimeType2(Uri.fromFile(fi)),lastModDate.toString());
Log.e(TAG, "file " + fi.toString() + " remote path " + mServerUri + " mime " + getMimeType2(Uri.fromFile(fi))+" date "+lastModDate.toString());
} catch (Exception e) {
Log.e(TAG, "eee " + e.toString());
}
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = {"_data"};
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
Though I just created a new folder using the api documentation and it works well good and created a folder! Although every this is working in good condition like reading a file from Next Cloud too!
The problem is with the image upload from the device! I am getting the following error while I am trying to upload:
Operation finished with HTTP status code 409 (fail)
I currently have no idea what I have been doing wrong, can somebody please give some idea about what is being done wrong!
HTTP Error 409 means that there is a confict with the resource on the server.
You should check the response from the server to understand how to resolve the confict.
More info: https://httpstatuses.com/409
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.
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).