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
Related
There is a function, adding user image to my app, but I need image to use again, so I chose SQLite Database to save path to image, my database works correctly. So in OnClick method, app show DialogWindow, where user choose image from gallery:
choosePath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
//Type - image:
photoPickerIntent.setType("image/*");
//Start activity, waiting for result
startActivityForResult(photoPickerIntent, Pick_image);
}
});
Then onActivityResult is called:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode){
case Pick_image:
if(requestCode == RESULT_OK){
try {
final Uri imageUri = imageReturnedIntent.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
Log.e("mLog", "onActivityResult: " + imageStream + " " + imageReturnedIntent + " " + imageUri);
pathToImage = imageUri.toString();
} catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
}
But when I save path in SQlite:
ContentValues cv = new ContentValues();
cv.put("description", description);
cv.put("image_link", pathToImage);
cv.put("category", category[0]);
long res = mDb.insert("favourites", null, cv);
if (res > -1) {
Toast.makeText(getApplicationContext(), "Шаблон добавлен в любимые", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Ошибка", Toast.LENGTH_SHORT).show();
}
I get exception:
E/SQLiteDatabase: Error inserting description=dog image_link=null category=
android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: favourites.image_link (code 1299 SQLITE_CONSTRAINT_NOTNULL)
I used debugger, but it didnt help me.
Please help me to solve this problem!
Correct your if condition, that causes your code not running inside if condition and getting pathToImage object null
// you are matching here request code with result status
if(requestCode == RESULT_OK)
//It should be
if(resultCode == RESULT_OK)
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();
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.
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).
This the code I am using to take picture, display it, then send it in an email:
private void takePicture() {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo = new File(Environment.getExternalStorageDirectory(),
getIntent().getStringExtra("counter"));
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, 0);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 0:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ContentResolver cr = getContentResolver();
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
savePicture(getIntent().getStringExtra("counter"), bitmap,
getApplicationContext());
setImage();
Toast.makeText(this, selectedImage.toString(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
}
}
}
}
How I send the email:
final Intent emailIntent = new Intent(
android.content.Intent.ACTION_SEND);
String fileName = null;
try {
fileName = URLEncoder.encode(getIntent().getStringExtra("counter"), "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String path = Environment.getExternalStorageDirectory()+"/"+fileName.trim().toString();
Uri uri = Uri.parse("file://"+path);
emailIntent.setType("image/png");
emailIntent.putExtra(android.content.Intent.EXTRA_STREAM, uri);
/* Send it off to the Activity-Chooser */
startActivity(Intent
.createChooser(emailIntent, "Send Email..."));
Notice, my file name should be getIntent().getStringExtra("counter");
When I do this, my email sends a text file rather than an image file. I have no clue why it does this...
I suspect this has happened to more than one person, but the problem was this:
I had to add +".jpg" to the end of the filename, and now it works. This may have been a simple solution but it surely was a distressful problem!
Hope this post still helps those who encounter this issue in the future.