I am new to android development, and I am using intent to choose a file locally so I can upload it to some cloud storage. I have been realizing a lot that the file names returned are in the form image:b for some number b. For example for a file I get path = /document/image:91 and filename = image:91. Does this mean that my result is wrong? I was expecting to get the actual file name. I just want to know if my code is correct.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "requestCode: " + requestCode);
Log.d(TAG, "resultCode: " + resultCode);
Log.d(TAG, "Actiity.RESULT_OK: " + Activity.RESULT_OK);
Log.d(TAG, "intent data: " + data);
if (requestCode == CHOOSE_FILE_REQUESTCODE && resultCode == Activity.RESULT_OK && null != data) {
Uri image = data.getData();
String path = image.getPath();
this.file = new File(path);
String filename = image.getLastPathSegment();
//File destination = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/CustomFolder/" + filename);
Log.d(TAG, "file name: " + filename);
Log.d(TAG, "file path: " + path);
this.fileName.setText(filename);
}
}
Start Intent.
public void onClickSelectPhoto(View v){
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(intent, CHOOSE_FILE_REQUESTCODE);
}
Related
I have created this app based on tutorials, ATM it successfully open the camera and displays it as imgOriginal on the screen. When i press the compress button I get a error relating to '.compressToFile(imageBitmap);
Error Message:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.photocompressor, PID: 11123
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.io.File.getName()' on a null object reference
at id.zelory.compressor.Compressor.compressToFile(Compressor.java:56)
at com.example.photocompressor.MainActivity$3.onClick(MainActivity.java:149)
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if (resultCode == RESULT_OK) {
// if (resultCode == RESULT_IMAGE && resultCode == RESULT_OK ) {
if (resultCode == RESULT_OK && resultCode != RESULT_IMAGE) {
btnCompress.setVisibility(View.VISIBLE);
final Uri imageUri = data.getData();
try {
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
imgOriginal.setImageBitmap(selectedImage);
////originalImage = new File(imageUri.getEncodedPath().replace("raw/", ""));
long size = DocumentFile.fromSingleUri(this, imageUri).length();
//txtOriginal.setText("Size: " + Formatter.formatShortFileSize(this, originalImage.length()));
txtOriginal.setText("Size: " + Formatter.formatShortFileSize(this, size));
Toast.makeText(MainActivity.this, "Size: " + size, Toast.LENGTH_LONG).show();
//Toast.makeText(MainActivity.this, "Size: " + Formatter.formatShortFileSize(this, originalImage.length()), Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, "Something went Wrong", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "No Image Selected", Toast.LENGTH_SHORT).show();
// }
Below is the compress button, error appears in '.compressToFile'. I would ideally like to have the option to replace the original file or to save as a new file, but havent even got the replace file to work yet.
btnCompress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int quality = seekBar.getProgress();
int width = Integer.parseInt(txtWidth.getText().toString());
int height = Integer.parseInt(txtHeight.getText().toString());
Toast.makeText(MainActivity.this, "Quality " + quality, Toast.LENGTH_SHORT).show();
try {
compressedImage = new Compressor(MainActivity.this)
.setMaxWidth(width)
.setMaxHeight(height)
.setQuality(quality)
.setCompressFormat(Bitmap.CompressFormat.JPEG)
.setDestinationDirectoryPath(filepath)
//.compressToFile(originalImage);
.compressToFile(imageBitmap);
File finalFile = new File(filepath, originalImage.getName());
Bitmap finalBitmap = BitmapFactory.decodeFile(finalFile.getAbsolutePath());
imgCompressed.setImageBitmap(finalBitmap);
//long newsize = DocumentFile.fromSingleUri(this, image);
//txtCompressed.setText("size: " + Formatter.formatShortFileSize(MainActivity.this,newsize));
//Toast.makeText(MainActivity.this, filepath + " Something went Wrong", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Error while Compressing", Toast.LENGTH_SHORT).show();
}
}
});
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)
I have this code :
public static final int RESULT_OK = -1;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri fileUri = data.getData();
File F = new File(fileUri.getPath());
Log.d("File", "File Uri: " + fileUri.toString());
Intent intent = new Intent(getContext(),activity_file_sharing.class);
intent.putExtra("Filepath", fileUri.toString());
startActivity(intent);
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
F.length() always return 0 i need to path the size of the selected file to the other activity
can anyone help
Please, check this link:
how do I get file size of temp file in android?
Try this:
File file = new File(selectedPath);
int file_size = Integer.parseInt(String.valueOf(file.length()/1024));
I have this code :
Activity 1
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri fileUri = data.getData();
Log.d("File", "File Uri: " + fileUri.toString());
Intent intent = new Intent(getContext(),activity_file_sharing.class);
intent.putExtra("Filepath", fileUri);
startActivity(intent);
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
In activity_file_sharing
Bundle extras = getIntent().getExtras();
if (extras != null && extras.containsKey("Filepath")) {
FPath = Uri.parse(getIntent().getStringExtra("Filepath").toString());
}
FPath = Uri.parse(getIntent().getStringExtra("Filepath").toString());
I am always getting a null reference on the line above , i can't figure out what is the problem
I hope you guys can help
Save it as a String:
Intent intent = new Intent(getContext(),activity_file_sharing.class);
intent.putExtra("Filepath", fileUri.toString());
startActivity(intent);
This is part of the code, and the question is, how can I INTENT this values
Log.i(TAG, "Display Name: " + person.getDisplayName());
Log.i(TAG, "Gender: " + person.getGender());
Log.i(TAG, "About Me: " + person.getAboutMe());
Log.i(TAG, "Birthday: " + person.getBirthday());
Log.i(TAG, "Current Location: " + person.getCurrentLocation());
Log.i(TAG, "Language: " + person.getLanguage());
To another activity.
My idea which do not work is to do it like this
userGenderG = person.getGender();
userAboutG = person.getAboutMe();
userBirthdayG = person.getBirthday();
userLanguageG = person.getLanguage();
Unsuccessful idea.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
// G+
if (mGoogleApiClient.hasConnectedApi(Plus.API)) {
Person person = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
if (person != null) {
Log.i(TAG, "--------------------------------");
Log.i(TAG, "Display Name: " + person.getDisplayName());
Log.i(TAG, "Gender: " + person.getGender());
Log.i(TAG, "About Me: " + person.getAboutMe());
Log.i(TAG, "Birthday: " + person.getBirthday());
Log.i(TAG, "Current Location: " + person.getCurrentLocation());
Log.i(TAG, "Language: " + person.getLanguage());
userGenderG = person.getGender();
userAboutG = person.getAboutMe();
userBirthdayG = person.getBirthday();
userLanguageG = person.getLanguage();
} else {
Log.e(TAG, "Error!");
}
} else {
Log.e(TAG, "Google+ not connected");
}
}
}
Any suggestion about how could I user gender as value and intent them to another activity?
UPDATED (how send data)
GoToNewActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Index.class);
Bundle extras = new Bundle();
extras.putString("userGender", userGenderG);
extras.putString("userAbout", userAboutG);
extras.putString("userBirthday", userBirthdayG);
extras.putString("userLanguage", userLanguageG);
intent.putExtras(extras);
startActivity(intent);
}
});