I am making a edit profile page , in which i display profile picture of the user the user can edit the profile picture . before clicking submit the i want to save the final updated url of profile picture . The problem is that if i change the profile picture and and instantly click on submit the value of variable storing the url doen not change but if i wait for few seconds it changes is there a way to get the value updated instantly.
**My edit profile class**
public class DocEditProfileInfo extends DocBaseActivity {
private static final String TAG =
private String profilePicUrl;
public String profilepicUrlComplete;
ArrayList<String> mImagesString = new ArrayList<>();
private ProgressBar imageProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ButterKnife.bind(this);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
imageProgressBar = (ProgressBar) findViewById(R.id.progress);
setUpRestAdapter();
setSalutation();
setDocPersonalDetails();
ImageView iv = (ImageView) findViewById(R.id.camera_new);
iv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setDialogForImage();
}
});
docSubmitInfo.setOnClickListener(this);
}
private void setDialogForImage() {
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.dialog_select_from_source);
Button btnCamera = (Button) dialog.findViewById(R.id.btnCamera);
Button btnDocs = (Button) dialog.findViewById(R.id.btnDoc);
btnDocs.setVisibility(View.INVISIBLE);
Button btnGallery = (Button) dialog.findViewById(R.id.btnGallery);
dialog.show();
btnCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
dialog.cancel();
}
});
btnGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, PICK_FROM_GALLERY);
dialog.cancel();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri mImageCaptureUri;
if (resultCode != RESULT_OK) {
return;
}
if (requestCode == 0 && resultCode == RESULT_OK) {
Bitmap bp = (Bitmap) data.getExtras().get("data");
// Uri selectedImageUri = data.getData();
// Glide.with(this).load(selectedImageUri).fitCenter().into(personImage);
personImage.setImageBitmap(getRoundedShape(bp));
// personImage.setImageBitmap(bp);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), bp);
// CALL THIS METHOD TO GET THE ACTUAL PATH
File filePath = new File(getRealPathFromURI(tempUri));
sendImagesToServerFromCamera(filePath.getPath());
} else if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK) {
/* Uri selectedImageUri = data.getData();
Log.e(TAG, "onActivityResult: URI " + selectedImageUri);
Glide.with(this).load(selectedImageUri).into(personImage);*/
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]);
String imgDecodableString = cursor.getString(columnIndex);
cursor.close();
// Set the Image in ImageView after decoding the String
personImage.setImageBitmap(getRoundedShape(BitmapFactory
.decodeFile(imgDecodableString)));
sendImagesToServerFromCamera(imgDecodableString);
}
}
public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
*******
}
private String getRealPathFromURI(Uri tempUri) {
********
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
*********
}
private void sendImagesToServerFromCamera(String path) {
File imgPath = new File(path);
Log.e(TAG, "PATH " + path);
RequestBody requestFile =
RequestBody.create(MediaType.parse("image/jpg"), imgPath);
//For sending all types of images , presently only jpg allowed
// RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), imgPath);
MultipartBody.Part body =
MultipartBody.Part.createFormData("file", imgPath.getName(), requestFile);
/* MultipartBody.Part body =
MultipartBody.Part.createFormData("file", imgPath.getName(), fbody);*/
Call<ProfilePicture> call = ProfilePicAdapter.sendProfilePic(body);
call.enqueue(new Callback<ProfilePicture>() {
#Override
public void onResponse(Call<ProfilePicture> call, Response<ProfilePicture> response) {
if (response.isSuccessful()) {
profilePicUrl = response.body().getUrl();
// profilepicUrlComplete = BASE_URL_FOR_IMAGE + profilePicUrl;
// String profilePicUrl = BASE_URL_FOR_IMAGE + profilePicUrl;
if (response.body().getUrl() != null) {
profilePicUrl = response.body().getUrl();
String profilePictureUrlComplete = BASE_URL_FOR_IMAGE + profilePicUrl;
setProfilePicURL(profilePictureUrlComplete);
}
} else {
Log.e(TAG, "UNSUCCESSFUL RESPONSE " + response.errorBody() + "*" + response.code());
}
}
#Override
public void onFailure(Call<ProfilePicture> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.toString());
}
});
}
private void setProfilePicURL(String profilePictureUrlComplete) {
profilepicUrlComplete = profilePictureUrlComplete;
Log.e(TAG, "setProfilePicURL: " + profilePictureUrlComplete);
}
private void setDocPersonalDetails() {
*********
}
#Override
public void onClick(View v) {
if (isEditProfileValid()) {
Log.e(TAG, "onClick: PROFILE URL " + profilepicUrlComplete);
***docPersonalDetailsUpdate.setProfilePic(profilepicUrlComplete);***
Call<DoctorProfile> call = docPersonalDetailsUpdateAdapter.docEditPersonalDetails(docPersonalDetailsUpdate);
if (NetworkUtils.isNetworkConnected(this)) {
call.enqueue(new Callback<DoctorProfile>() {
#Override
public void onResponse(Call<DoctorProfile> call, Response<DoctorProfile> response) {
if (response.isSuccessful()) {
finish();
}
}
#Override
public void onFailure(Call<DoctorProfile> call, Throwable t) {
Log.e(TAG, "onFailure: ");
}
});
} else {
SnakBarUtils.networkConnected(this);
}
}
Related
I want to send image as well as data using volley help me i need simplest way to send it please help me i have tried in postman where i selected the file rather than text and send all went well i need like that.
Map<String, String> params = new HashMap<String, String>();
params.put("number", strUserName.trim());
params.put("image", image);
JSONObject json = new JSONObject(params);
String url = "";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url
, json, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject object = new JSONObject(String.valueOf(response));
String status = object.getString("Status");
if (status.equals("200")) {
Intent intent = new Intent(MainActivity.this, OtpVerification.class);
intent.putExtra("mobile1",strUserName);
startActivity(intent);
finish();
} else if(status.equals("404")) {
Toast.makeText(MainActivity.this, "Please Enter Valid No.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Log.e("Ashish", " " + e);
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(jsonObjectRequest);
}
I have tried this now but its shopwing me the error my value on addstring are not passing they are sending empty as i am directly putting the value too.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
btnChoose = findViewById(R.id.button_choose);
btnUpload = findViewById(R.id.button_upload);
btnChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
imageBrowse();
}
});
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (filePath != null) {
imageUpload(filePath);
} else {
Toast.makeText(getApplicationContext(), "Image not selected!", Toast.LENGTH_LONG).show();
}
}
});
}
private void imageBrowse() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == PICK_IMAGE_REQUEST) {
Uri picUri = data.getData();
filePath = getPath(picUri);
Log.d("picUri", picUri.toString());
Log.d("filePath", filePath);
imageView.setImageURI(picUri);
}
}
}
private void imageUpload(final String imagePath) {
SimpleMultiPartRequest smr1= new SimpleMultiPartRequest(Request.Method.POST, BASE_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", response);
try {
JSONObject jObj = new JSONObject(response);
String message = jObj.getString("status");
if (message.equals("201")) {
Toast.makeText(getApplicationContext(), message + "Done", Toast.LENGTH_LONG).show();
} else if (message.equals("200")) {
Toast.makeText(getApplicationContext(), message + "Done", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
smr1.addStringParam("a_k_s_no", "1112");
smr1.addStringParam("year", "2020");
smr1.addStringParam("month", "01");
smr1.addStringParam("token", "5c041062bf7ab2a409f910ab34fe6e1e");
smr1.addFile("fileToUpload", imagePath);
MyApplication.getInstance().addToRequestQueue(smr1);
}
private String getPath(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
CursorLoader loader = new CursorLoader(getApplicationContext(), contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
Sample Code :
Volley Image Upload Layout
For creating the above layout you can use the following xml code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Upload Image using Volley"
android:id="#+id/textView"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="10dp"/>
<Button
android:id="#+id/button_choose"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
android:text="Browse Image"
android:textColor="#fff"
android:layout_gravity="center_horizontal"
android:layout_margin="20dp"
android:padding="10dp"/>
<ImageView
android:id="#+id/imageView"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="#drawable/border"
android:layout_gravity="center_horizontal"
android:padding="5dp"
android:layout_margin="20dp"/>
<Button
android:id="#+id/button_upload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
android:text="upload"
android:textColor="#fff"
android:layout_gravity="center_horizontal"
android:layout_margin="20dp"/>
</LinearLayout>
Now lets come to MainActivity.java
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private Button btnChoose, btnUpload;
public static String BASE_URL = "http://192.168.1.100/AndroidUploadImage/upload.php";
static final int PICK_IMAGE_REQUEST = 1;
String filePath;
Now implement OnClickListener interface to our buttons.
btnChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
imageBrowse();
}
});
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (filePath != null) {
imageUpload(filePath);
} else {
Toast.makeText(getApplicationContext(), "Image not selected!", Toast.LENGTH_LONG).show();
}
}
});
Now we will create a method to choose image from gallery. Create the following method.
private void imageBrowse() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
}
To complete the image choosing process we need to override the following method.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if(requestCode == PICK_IMAGE_REQUEST){
Uri picUri = data.getData();
filePath = getPath(picUri);
imageView.setImageURI(picUri);
}
}
}
// Get Path of selected image
private String getPath(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(getApplicationContext(), contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
More information about Android Images, read chapter Amazing Facts of Android ImageView.
Now run your application and if you can choose image from gallery then you can move ahead. In below snapshot you can see mine app is working.Image Upload Using Volley
Now we need to create one more method that will upload the image to our server. Create the following method in MainActivity class.
private void imageUpload(final String imagePath) {
SimpleMultiPartRequest smr = new SimpleMultiPartRequest(Request.Method.POST, BASE_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", response);
try {
JSONObject jObj = new JSONObject(response);
String message = jObj.getString("message");
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
smr.addFile("image", imagePath);
MyApplication.getInstance().addToRequestQueue(smr);
}
So the final complete code for our MainActivity.java file would be like
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private Button btnChoose, btnUpload;
public static String BASE_URL = "http://192.168.1.100/AndroidUploadImage/upload.php";
static final int PICK_IMAGE_REQUEST = 1;
String filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
btnChoose = (Button) findViewById(R.id.button_choose);
btnUpload = (Button) findViewById(R.id.button_upload);
btnChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
imageBrowse();
}
});
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (filePath != null) {
imageUpload(filePath);
} else {
Toast.makeText(getApplicationContext(), "Image not selected!", Toast.LENGTH_LONG).show();
}
}
});
}
private void imageBrowse() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if(requestCode == PICK_IMAGE_REQUEST){
Uri picUri = data.getData();
Log.d("picUri", picUri.toString());
Log.d("filePath", filePath);
imageView.setImageURI(picUri);
}
}
}
private void imageUpload(final String imagePath) {
SimpleMultiPartRequest smr = new SimpleMultiPartRequest(Request.Method.POST, BASE_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", response);
try {
JSONObject jObj = new JSONObject(response);
String message = jObj.getString("message");
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
smr.addFile("image", imagePath);
MyApplication.getInstance().addToRequestQueue(smr);
}
// Get Path of selected image
private String getPath(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(getApplicationContext(), contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
}
Now at last add below permission to your application.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
MyApplication.java
public class MyApplication extends Application {
public static final String TAG = MyApplication.class.getSimpleName();
private RequestQueue mRequestQueue;
private static MyApplication mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Hope this will work!
I am trying to use Ucrop from a fragment. The issue I am facing is that onActivityresult is not receiving requestCode == UCrop.REQUEST_CROP thus not performing the actions I need to do with the image. I have searched around for tutorials but I haven't managed to find any.
The following is the code of the fragment that is using UCrop:
public class FragmentSettingsTabImage extends Fragment {
private String TAG = "----->";
Tools t;
private String currentPhotoPath;
private final int REQUEST_TAKE_PHOTO = 1;
private final int CAMERA_PERMISSIONS = 2;
private ImageView imgTabImageDriver;
private Button btnSettingsSaveImage;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == CAMERA_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// All good so launch take picture from here
dispatchTakePictureIntent();
} else {
// Permission denied. Warn the user and kick out of app
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.permsDeniedCameraTitle);
builder.setMessage(R.string.permsDeniedCameraMessage);
builder.setCancelable(false);
builder.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Objects.requireNonNull(getActivity()).finishAffinity();
}
});
builder.create().show();
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK) {
Uri starturi = Uri.fromFile(new File(currentPhotoPath));
Uri destinationuri = Uri.fromFile(new File(currentPhotoPath));
UCrop.Options options = AppConstants.makeUcropOptions(Objects.requireNonNull(getActivity()));
UCrop.of(starturi, destinationuri).withOptions(options).start(getActivity());
}
Log.d(TAG, "onActivityResult: CCCCCCC" + resultCode + " " + requestCode);
// On result from cropper add to imageview
getActivity();
if (resultCode == Activity.RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
final Uri resultUri = UCrop.getOutput(data);
assert resultUri != null;
File imgFile = new File(resultUri.getPath());
Picasso.Builder builder = new Picasso.Builder(Objects.requireNonNull(getActivity()));
builder.listener(new Picasso.Listener() {
#Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
exception.printStackTrace();
}
});
builder.build().load(imgFile).into(imgTabImageDriver, new Callback() {
#Override
public void onSuccess() {
btnSettingsSaveImage.setEnabled(true);
}
#Override
public void onError(Exception e) {
e.printStackTrace();
}
});
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
SharedPreferences preferences = Objects.requireNonNull(this.getActivity()).getSharedPreferences("mykago-driver", Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = preferences.edit();
View view = inflater.inflate(R.layout.fragment_settings_tab_image, container, false);
imgTabImageDriver= view.findViewById(R.id.imgTabImageDriver);
ImageView imgTakeSettingsDriverPicture = view.findViewById(R.id.imgTakeSettingsDriverPicture);
btnSettingsSaveImage = view.findViewById(R.id.btnSettingsSaveImage);
imgTakeSettingsDriverPicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
imgTabImageDriver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
btnSettingsSaveImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor.putString("driver_picture", currentPhotoPath);
editor.apply();
}
});
Picasso.Builder builder = new Picasso.Builder(Objects.requireNonNull(getContext()));
builder.listener(new Picasso.Listener() {
#Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
exception.printStackTrace();
}
});
Log.d(TAG, "onCreateView: " + preferences.getString("driver_picture", ""));
builder.build().load(new File(preferences.getString("id_picture", ""))).into(imgTabImageDriver);
return view;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(Objects.requireNonNull(getActivity()).getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.d("IMAGE CREATION", ex.toString());
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(getActivity(),
"com.mytestapp.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
String imageFileName = "didimage_" + timeStamp + "_";
File storageDir = Objects.requireNonNull(getActivity()).getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName,
".png",
storageDir
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
}
The same code from a normal activity works without any issues. Any help appreciated.
Managed to solve the issue. To pass the result of the UCrop activity to the fragment and not to the hosting activity you need to call the UCrop....start() method as follows:
UCrop.of(starturi, destinationuri).withOptions(options).start(getActivity().getApplicationContext(), getFragmentManager().findFragmentByTag("your_fragment_tag"));
so
.start(Context, Fragment)
This will make sure that the onActivityResult of the fragment gets called and not the one of the hosting activity.
This works also:
UCrop.of(sourceUri,destinationUri)
.withOptions(options)
.start(getActivity(),YourFragment.this);
If you want to start uCrop activity from Fragment use this.
UCrop.of(uri, destinationFileName)
.withAspectRatio(1, 1)
.start(getContext(), this, UCrop.REQUEST_CROP);
i am uploading video to firebase storage. i want to show the thumbnail of selected video on app screen
i have tried uploading image with the same code and it gives me the image preview of selected image, but it doesnot show any preview or thumbnail of selected video
moreover i want to know hoe to give the path of selected video as well..
main activity
public class MainActivity extends AppCompatActivity {
private static final int PICK_VIDEO_REQUEST = 3;
Button chooseImg, uploadImg;
ImageView imgView;
int PICK_IMAGE_REQUEST = 111;
Uri filePath;
ProgressDialog pd;
//creating reference to firebase storage
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://<<ur app url>>"); //change the url according to your firebase app
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chooseImg = (Button)findViewById(R.id.chooseImg);
uploadImg = (Button)findViewById(R.id.uploadImg);
imgView = (ImageView)findViewById(R.id.imgView);
pd = new ProgressDialog(this);
pd.setMessage("Uploading....");
chooseImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(intent, "Select Video"), PICK_VIDEO_REQUEST);
}
});
uploadImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(filePath != null) {
pd.show();
StorageReference childRef = storageRef.child("vide.mp4");
//uploading the image
UploadTask uploadTask = childRef.putFile(filePath);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
pd.dismiss();
Toast.makeText(MainActivity.this, "Upload successful", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(MainActivity.this, "Upload Failed -> " + e, Toast.LENGTH_SHORT).show();
}
});
}
else {
Toast.makeText(MainActivity.this, "Select a video", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
//getting image from gallery
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting image to ImageView
imgView.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
I am using the Fabric of the Twitter for sharing the video.I am not able to share the video on the twitter and yet now i am sharing the images only by the help of Fabric
Below is my lines of code for the fabric integration
public class MainActivity extends AppCompatActivity {
// Note: Your consumer key and secret should be obfuscated in your source code before shipping.
private static final String TWITTER_KEY = "xxxxxxx";
private static final String TWITTER_SECRET = "xxxxxxxxxxxxxxxxxxxxxxxxx";
private TwitterAuthClient authclient;
private TwitterLoginButton loginButton;
private String selectedImagePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
Fabric.with(this, new Twitter(authConfig));
setContentView(R.layout.activity_main);
authclient = new TwitterAuthClient();
loginButton = (TwitterLoginButton) findViewById(R.id.twitter_login_button);
loginButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
// The TwitterSession is also available through:
// Twitter.getInstance().core.getSessionManager().getActiveSession()
TwitterSession session = result.data;
// TODO: Remove toast and use the TwitterSession's userID
// with your app's user model
String msg = "#" + session.getUserName() + " logged in! (#" + session.getUserId() + ")";
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
#Override
public void failure(TwitterException exception) {
Log.d("TwitterKit", "Login with Twitter failure", exception);
}
});
Button share_btn = (Button)findViewById(R.id.share_btn);
share_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
intent.setType("video/*");
startActivityForResult(intent, 3);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
try {
if (requestCode == 3) {
Uri selectedImageUri = data.getData();
// OI FILE Manager
selectedImagePath = selectedImageUri.getPath();
// MEDIA GALLERY
selectedImagePath = getPath(selectedImageUri);
System.out.println("Here is the data ==>> " + selectedImagePath+" ");
TweetComposer.Builder builder = new TweetComposer.Builder(MainActivity.this)
.text("")
.image(Uri.parse(selectedImagePath));
builder.show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public String getPath(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}
I have got the solution for uploading the video using Twitter's Fabrics
Here is the below lines of code to upload the video on Twitter , using the Fabric
File myVideoFile = new File("HERE_IS_YOURS_SD_CARD_VIDEO_PATH");
Uri myVideoUri = Uri.fromFile(myVideoFile);
TweetComposer.Builder builder = new TweetComposer.Builder(MainActivity.this)
.text("YOUR_TEXT_MESSAGE") //Here is yours message which you want to send..If u does not require than remove this method
.image(myVideoUri );
builder.show();
The complete code of my Fragment:
public class ProfileEditPictureFragment extends BaseFragment implements OnClickListener {
private ImageView imageView = null;
private Button buttonPick = null;
private Button buttonSave = null;
private Button buttonCancel = null;
private File tempFile = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRetainInstance(true);
this.sessionProfilePreferences = new SessionProfilePreferences(this.getActivity());
this.sessionLoginPreferences = new SessionLoginPreferences(this.getActivity());
this.sessionLoginSingleton = SessionLoginSingleton.getInstance(this.getActivity());
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
this.tempFile = new File(Environment.getExternalStorageDirectory(), "temp_photo.jpg");
}
else {
this.tempFile = new File(this.getActivity().getFilesDir(), "temp_photo.jpg");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_profile_picture_edit, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.imageView = (ImageView) view.findViewById(R.id.profile_picture_edit_imageview_photo);
this.buttonPick = (Button) view.findViewById(R.id.profile_picture_edit_button_pick);
this.buttonPick.setOnClickListener(this);
this.buttonSave = (Button) view.findViewById(R.id.profile_picture_edit_button_save);
this.buttonSave.setOnClickListener(this);
this.buttonCancel = (Button) view.findViewById(R.id.profile_picture_edit_button_cancel);
this.buttonCancel.setOnClickListener(this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v("ProfileEditPicture", "requestCode: " + requestCode);
Log.v("ProfileEditPicture", "resultCode: " + resultCode);
Log.v("ProfileEditPicture", "data: " + data);
Bitmap bitmap = null;
if(resultCode == Activity.RESULT_OK) {
if (requestCode == Globals.REQUEST_PICK_PHOTO) {
try {
InputStream inputStream = this.getActivity().getContentResolver().openInputStream(data.getData());
FileOutputStream fileOutputStream = new FileOutputStream(this.tempFile);
Helper.copyStream(inputStream, fileOutputStream);
fileOutputStream.close();
inputStream.close();
this.startCropImage();
} catch (Exception e) {}
} else if (requestCode == Globals.REQUEST_CROP_PHOTO) {
String path = data.getStringExtra(CropActivity.IMAGE_PATH);
if (path == null) {
return;
}
bitmap = BitmapFactory.decodeFile(this.tempFile.getPath());
this.imageView.setImageBitmap(bitmap);
}
}
}
#Override
public void onClick(View view) {
switch(view.getId()) {
case R.id.profile_picture_edit_button_pick : {
this.pickPicture();
} break;
case R.id.profile_picture_edit_button_save : {
} break;
case R.id.profile_picture_edit_button_cancel : {
this.getActivity().finish();
}
}
}
private void pickPicture() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
this.startActivityForResult(Intent.createChooser(intent, "Select Picture"), Globals.REQUEST_PICK_PHOTO);
}
private void startCropImage() {
Intent intent = new Intent(this.getActivity(), CropActivity.class);
intent.putExtra(CropActivity.IMAGE_PATH, this.tempFile.getPath());
intent.putExtra(CropActivity.SCALE, true);
intent.putExtra(CropActivity.ASPECT_X, 3);
intent.putExtra(CropActivity.ASPECT_Y, 2);
this.startActivityForResult(intent, Globals.REQUEST_CROP_PHOTO);
}
}
But the resultCode is always 0 and the data is always null. Permissions are set ofcourse.
So how can i pick images from the gallery?
I test it on Nexus 4 with Android 5.0.1
Try ACTION_PICK like this
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
And on Activity result
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == RESULT_LOAD_IMG && 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]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
I was having same problem in one of my activities when I set launchMode="singleInstance" in manifest for that activity. It works fine when I remove that attribute. Although I don't know reason for this behaviour.