Android share intent for facebook- share text AND link - android

I am trying to use the Android share intent to post something on facebook. It looks like this:
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.setType("text/plain");
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Free education for all! http://linkd.in/xU8mCc");
startActivity(shareIntent);
So my post has both - some text and a link. But when the message is posted on facebook, it only has the link, no message. I tried various extras but nothing works.
Anyone faced this issue and solved it? I have facebook app version 1.8.1
Edit: I tried removing the link, and the facebook app does not take my message (shows a blank message to be posted), but not the other way round. So looks like the app is totally ignoring any plain text messages. I am spooked! Is this a major bug in the fb app that text messages can not be posted at all (with share intent)?

I just built this code and it's working for me:
private void shareAppLinkViaFacebook(String urlToShare) {
try {
Intent intent1 = new Intent();
intent1.setClassName("com.facebook.katana", "com.facebook.katana.activity.composer.ImplicitShareIntentHandler");
intent1.setAction("android.intent.action.SEND");
intent1.setType("text/plain");
intent1.putExtra("android.intent.extra.TEXT", urlToShare);
startActivity(intent1);
} catch (Exception e) {
// If we failed (not native FB app installed), try share through SEND
String sharerUrl = "https://www.facebook.com/sharer/sharer.php?u=" + urlToShare;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(sharerUrl));
startActivity(intent);
}
}

If you are going to use the regular Android Sharing Intents, then unfortunately the Facebook sharing intent can only take a single URL (make sure it has http://) and no additional text message. It is a strange limitation that doesn't really make sense.
You have to use the actual official separate Facebook Android SDK in your project to get the full sharing functionality. Which is extra work.
I ran in to similar issues. In the end, what I did was branch the intent. If they choose to share (in the regular android share intent) via Facebook, create a new share intent that only has the URL and push that to facebook. All other share options (twitter, message, email) would work like normal.
my question and solution are here:
Branching the Android Share Intent extras depending on which method they choose to share
String shareBody = "app string text " + act_txt + " more text! Get the app at http://www.appurl.com";
PackageManager pm = view.getContext().getPackageManager();
List<ResolveInfo> activityList = pm.queryIntentActivities(sharingIntent, 0);
for(final ResolveInfo app : activityList) {
Log.i(TAG, "app.actinfo.name: " + app.activityInfo.name);
//if((app.activityInfo.name).contains("facebook")) {
if("com.facebook.katana.ShareLinkActivity".equals(app.activityInfo.name)) {
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "http://www.appurl.com");
startActivity(Intent.createChooser(sharingIntent, "Share idea"));
break;
} else {
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "app name");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share"));
break;
}
}

In Lollipop (21), you can use Intent.EXTRA_REPLACEMENT_EXTRAS to override the intent for specific apps.
https://developer.android.com/reference/android/content/Intent.html#EXTRA_REPLACEMENT_EXTRAS
private void doShareLink(String text, String link) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
Intent chooserIntent = Intent.createChooser(shareIntent, getString(R.string.share_via));
// for 21+, we can use EXTRA_REPLACEMENT_EXTRAS to support the specific case of Facebook
// (only supports a link)
// >=21: facebook=link, other=text+link
// <=20: all=link
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
shareIntent.putExtra(Intent.EXTRA_TEXT, text + " " + link);
Bundle facebookBundle = new Bundle();
facebookBundle.putString(Intent.EXTRA_TEXT, link);
Bundle replacement = new Bundle();
replacement.putBundle("com.facebook.katana", facebookBundle);
chooserIntent.putExtra(Intent.EXTRA_REPLACEMENT_EXTRAS, replacement);
} else {
shareIntent.putExtra(Intent.EXTRA_TEXT, link);
}
chooserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(chooserIntent);
}

In my app I have integrated Facebook SDK to enable users share the quote [ pre filled text ] on their wall. Using FB SDK, it is possible to do this. It works in my app and I have more than 5K users using the same.
Apparently this is not against the policy of FB as I have not had any warning or an issue where this did not work.
The code snippets for the same can be found here,
Do any widely used Android apps have Facebook sharing with pre-populated text field?

USe this code for share image ,video,link and text on facebook working perfectally
public class Shareonwall extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
JSONObject response, profile_pic_data, profile_pic_url;
TextView user_name, user_email;
ImageView user_picture;
NavigationView navigation_view;
CallbackManager callbackManager;
ShareDialog shareDialog;
int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;
private Uri fileUri;
// public static TextView output;
private static final int MY_PERMISSIONS_REQUEST_CAMERA = 110;
private static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 222;
private static final int MY_PERMISSIONS_REQUEST_CAMERA_VIDEO = 333;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
facebookSDKInitialize();
setContentView(R.layout.activity_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
Button button = (Button) findViewById(R.id.button);
Button imageShare = (Button) findViewById(R.id.imageShare);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Home Page");
Intent intent = getIntent();
String jsondata = intent.getStringExtra("jsondata");
setNavigationHeader(); // call setNavigationHeader Method.
setUserProfile(jsondata); // call setUserProfile Method.
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
shareDialog = new ShareDialog(this); // intialize facebook shareDialog.
navigation_view.setNavigationItemSelectedListener(this);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ShareDialog.canShow(ShareLinkContent.class)) {
ShareLinkContent linkContent = new ShareLinkContent.Builder()
.setContentTitle("How to integrate Facebook from your app")
.setImageUrl(Uri.parse("http://www.devglan.com/image/dashboard.jpg"))
.setContentDescription(
"simple Fb Image share integration")
.setContentUrl(Uri.parse("http://www.devglan.com/image/dashboard.jpg"))
.build();
shareDialog.show(linkContent); // Show facebook ShareDialog
}
}
});
imageShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
// this method is for create a dialog box to choose options to select Image to share on facebook.
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library","Record Video",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(Shareonwall.this);
builder.setTitle("Select profile Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
if (Build.VERSION.SDK_INT >= 23) {
if ((ContextCompat.checkSelfPermission(Shareonwall.this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(Shareonwall.this,
android.Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED)) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else {
if ((ContextCompat.checkSelfPermission(Shareonwall.this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(Shareonwall.this,
android.Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED)) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else {
ActivityCompat.requestPermissions(Shareonwall.this,
new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_CAMERA);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
}
} else {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);;
}
} else if (items[item].equals("Choose from Library")) {
if (Build.VERSION.SDK_INT >= 23) {
if ((ContextCompat.checkSelfPermission(Shareonwall.this,
android.Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED)) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);
} else {
if ((ContextCompat.checkSelfPermission(Shareonwall.this,
android.Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED)) {
} else {
ActivityCompat.requestPermissions(Shareonwall.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
}
} else {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);
}
} if (items[item].equals("Record Video")) {
if (Build.VERSION.SDK_INT >= 23) {
if ((ContextCompat.checkSelfPermission(Shareonwall.this,
android.Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED)) {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takeVideoIntent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
}
} else {
if ((ContextCompat.checkSelfPermission(Shareonwall.this,
android.Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED)) {
} else {
ActivityCompat.requestPermissions(Shareonwall.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_CAMERA_VIDEO);
}
}
} else {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takeVideoIntent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
}
}
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE){
onSelectFromGalleryResult(data);
}
else if (requestCode == REQUEST_CAMERA){
onCaptureImageResult(data);
}
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
// Uri videoUri = data.getData();
// mVideoView.setVideoURI(videoUri);
// recordVideo(videoUri);
String selectedVideoFilePath = GetFilePathFromDevice.getPath(this, data.getData());
final byte[] datas;
try {
datas = readBytes(selectedVideoFilePath,data.getData());
PostVideo(datas, selectedVideoFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public byte[] readBytes(String dataPath,Uri uri) throws IOException {
InputStream inputStream = new FileInputStream(dataPath);
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
ShareDialogVideo(uri);
return byteBuffer.toByteArray();
}
public void PostVideo(byte[] VideoBytes, String filePath) {
String url;
url = "/me/videos";
AccessToken token = AccessToken.getCurrentAccessToken();
if (token != null) {
Bundle param = new Bundle();
param.putByteArray("video." + getFileExt(filePath), VideoBytes);
param.putString("description", "sample video");
new GraphRequest(token,url, param, HttpMethod.POST, new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
Log.e("New Post", "Res =" + response.toString());
// dialog.dismiss();
if (response != null && response.getJSONObject() != null && response.getJSONObject().has("id")) {
Log.e("New Post", "Success");
Toast.makeText(Shareonwall.this, "Video posted successfully.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(Shareonwall.this, "Error in posting Video.", Toast.LENGTH_SHORT).show();
}
setResult(Activity.RESULT_OK, new Intent());
finish();
}
}).executeAsync();
}
}
public static String getFileExt(String fileName) {
return fileName.substring((fileName.lastIndexOf(".") + 1), fileName.length());
}
/**** this method used for select image From Gallery *****/
private void onSelectFromGalleryResult(Intent data) {
Uri selectedImageUri = data.getData();
String[] projection = { MediaStore.MediaColumns.DATA };
Cursor cursor = managedQuery(selectedImageUri, projection, null, null,
null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
Bitmap thumbnail;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, options);
final int REQUIRED_SIZE = 200;
int scale = 1;
while (options.outWidth / scale / 2 >= REQUIRED_SIZE
&& options.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
options.inSampleSize = scale;
options.inJustDecodeBounds = false;
thumbnail = BitmapFactory.decodeFile(selectedImagePath, options);
ShareDialog(thumbnail);
}
/*** this method used for take profile photo *******/
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ShareDialog(thumbnail);
}
// This method is used to share Image on facebook timeline.
public void ShareDialog(Bitmap imagePath){
SharePhoto photo = new SharePhoto.Builder()
.setBitmap(imagePath)
.setCaption("Testing")
.build();
SharePhotoContent content = new SharePhotoContent.Builder()
.addPhoto(photo)
.build();
shareDialog.show(content);
}
public void ShareDialogVideo(Uri imagePath){
ShareVideo shareVideo = new ShareVideo.Builder()
.setLocalUrl(imagePath)
.build();
ShareVideoContent content = new ShareVideoContent.Builder()
.setVideo(shareVideo)
.build();
shareDialog.show(content);
}
// Initialize the facebook sdk and then callback manager will handle the login responses.
protected void facebookSDKInitialize() {
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
/*
Set Navigation header by using Layout Inflater.
*/
public void setNavigationHeader(){
navigation_view = (NavigationView) findViewById(R.id.nav_view);
View header = LayoutInflater.from(this).inflate(R.layout.nav_header_home, null);
navigation_view.addHeaderView(header);
user_name = (TextView) header.findViewById(R.id.username);
user_picture = (ImageView) header.findViewById(R.id.profile_pic);
user_email = (TextView) header.findViewById(R.id.email);
}
/*
Set User Profile Information in Navigation Bar.
*/
public void setUserProfile(String jsondata){
try {
response = new JSONObject(jsondata);
user_email.setText(response.get("email").toString());
user_name.setText(response.get("name").toString());
profile_pic_data = new JSONObject(response.get("picture").toString());
profile_pic_url = new JSONObject(profile_pic_data.getString("data"));
Picasso.with(this).load(profile_pic_url.getString("url"))
.into(user_picture);
} catch (Exception e){
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
protected void onResume() {
super.onResume();
// Logs 'install' and 'app activate' App Events.
AppEventsLogger.activateApp(this);
}
#Override
protected void onPause() {
super.onPause();
// Logs 'app deactivate' App Event.
AppEventsLogger.deactivateApp(this);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);
} else {
}
return;
}
case MY_PERMISSIONS_REQUEST_CAMERA: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else {
}
return;
}
case MY_PERMISSIONS_REQUEST_CAMERA_VIDEO :{
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takeVideoIntent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
}
}
// other 'case' lines to check for other
// permissions this app might request
}
}
}

Related

How to build a URL in Koush ion

I am building an app to upload images to my company server
I am using koush-ion for the upload,
now my problem is I have to dynamically change the URL for upload depending on information entered in another activity(LoginActivity) via edittext boxes
and I don't understand how to do that
so what I want to happen is the client enters thier Email, password and clientID(4 digits)(in LoginActivity) and the app uses that to build a url for the upload
like this one(in CameraActivity)
https://www.blahpractice.co.za/files-upload-ruben.asp?MyForm=Yes&ClientID=1234&Username=man#blahpractice.co.za&Pwd=BlahBlah123#
I got this From the koush github, and i am unsure if this is what i am looking for and also how to implement data from another activity in koush-ion
Post application/x-www-form-urlencoded and read a String
Ion.with(getContext())
.load("https://koush.clockworkmod.com/test/echo")
.setBodyParameter("goop", "noop")
.setBodyParameter("foo", "bar")
.asString()
.setCallback(...)
Camera Activity
public class CameraActivity extends AppCompatActivity implements
View.OnClickListener{
private final int PICK_IMAGE = 12345;
private final int REQUEST_CAMERA = 6352;
private static final int REQUEST_CAMERA_ACCESS_PERMISSION =5674;
private Bitmap bitmap;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
imageView =findViewById(R.id.imageView);
Button fromCamera=findViewById(R.id.fromCamera);
Button fromGallery=findViewById(R.id.fromGallery);
Button upload=findViewById(R.id.upload);
upload.setOnClickListener(this);
fromCamera.setOnClickListener(this);
fromGallery.setOnClickListener(this);
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) {
fromCamera.setVisibility(View.GONE);
}
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.fromCamera:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_ACCESS_PERMISSION);
}else {
getImageFromCamera();
}
break;
case R.id.fromGallery:
getImageFromGallery();
break;
case R.id.upload:
if (bitmap != null)
uploadImageToServer();
break;
}
}
private void uploadImageToServer() {
I want to call the url here
File imageFile = persistImage(bitmap, "SP_Upload");
Ion.with(this)
.load("https://www.Blahpractice.co.za/files-upload-ruben.asp?MyForm=Yes")
.setMultipartFile("SP-LOG", "image/jpeg", imageFile)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception e, JsonObject result) {
}
});
}
private File persistImage(Bitmap bitmap, String name) {
File filesDir = getApplicationContext().getFilesDir();
File imageFile = new File(filesDir, name + ".jpg");
OutputStream os;
try {
os = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.flush();
os.close();
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
}
return imageFile;
}
private void getImageFromCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
private void getImageFromGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE) {
if (resultCode == Activity.RESULT_OK) {
try {
InputStream inputStream = getContentResolver().openInputStream(data.getData());
bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} else if (requestCode == REQUEST_CAMERA) {
if (resultCode == Activity.RESULT_OK) {
Bundle extras = data.getExtras();
bitmap = (Bitmap) extras.get("data");
imageView.setImageBitmap(bitmap);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_CAMERA_ACCESS_PERMISSION) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getImageFromCamera();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
LoginActivity
public class LoginActivity extends AppCompatActivity {
private EditText email, password, id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email=findViewById(R.id.emailtext);
password=findViewById(R.id.pwdtext);
id=findViewById(R.id.clientid);
Button loginBtn=findViewById(R.id.button);
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String emailAddress=email.getText().toString().trim();
String userPassword=password.getText().toString().trim();
String clientId=id.getText().toString().trim();
Intent intent=new Intent(LoginActivity.this, CameraActivity.class);
intent.putExtra("clientId", clientId);
intent.putExtra("email", emailAddress);
intent.putExtra("password", userPassword);
startActivity(intent);
}
});
}
}
You could store the url on the shared preferences and retrieve it every time you execute your upload task and set it on the .load() method.
Also, what you need to send an image to your server is a multipart post. I haven't used Ion but I have used multipart in other libraries like OkHttp, I´ve copied the method that appears on the Ion documentation:
String dynamicUrl = PreferenceManager.getDefaultSharedPreferences(context).getString(CURRENT_SELECTED_URL, null);
File myImage = new File(myImagePath);
if(dynamicUrl != null) {
Ion.with(getContext())
.load(dynamicUrl)
.uploadProgressBar(uploadProgressBar)
.setMultipartParameter("goop", "noop")
.setMultipartFile("myImageName", "image/*", myImage)
.asJsonObject()
.setCallback(...)
}

no popup for android webview to upload files or open camera

I couldn't get popup for my android webview app, I have tried everything possible could someone help me please, here is my mainActivity code.
What I am trying to do is to load my webview which I get successfully but there is a personal page where if a user click on profile picture it should prompt either to open camera or load image from galler and again there is an upload option if pressed same thing should happen either to upload photos or open camera, Its working fine if I do it from my browser but not from my webview android app
public class MainActivity extends AppCompatActivity {
private static final int MY_BLINK_ID_REQUEST_CODE = 0x101;
public static final int REQUEST_PERMISSION_READ_EXTERNAL_STORAGE = 101;
private static final int REQUEST_WEBFORM = 300;
public static final int REQUEST_SELECT_FILE = 100;
private ValueCallback<Uri> mUploadMessage;
private ValueCallback<Uri[]> uploadMessageLP;
private Uri directUploadImageUri;
private static final String TAG = MainActivity.class.getSimpleName();
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupToolbar();
loadHtml();
}
public void cancelFileUpload() {
if (mUploadMessage != null) {
mUploadMessage.onReceiveValue(null);
mUploadMessage = null;
}
if (uploadMessageLP != null) {
uploadMessageLP.onReceiveValue(null);
uploadMessageLP = null;
}
this.directUploadImageUri = null;
}
public void setUploadMessageLP(ValueCallback<Uri[]> uploadMessageLP) {
this.uploadMessageLP = uploadMessageLP;
}
/**
* setup toolbar
*/
private void setupToolbar() {
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//change title color
toolbar.setTitleTextColor(ContextCompat.getColor(this, R.color.white));
//set title
getSupportActionBar().setTitle(getString(R.string.app_name));
}
private void loadHtml() {
mWebView = (WebView) findViewById(R.id.wv);
mWebView.setWebViewClient(new WebViewClient());
WebSettings settings = mWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setLoadWithOverviewMode(true);
settings.setUseWideViewPort(true);
settings.setAllowContentAccess(true);
settings.setAllowFileAccess(true);
settings.setAllowFileAccessFromFileURLs(true);
settings.setAllowUniversalAccessFromFileURLs(true);
// Render the HTML file on WebView
mWebView.loadUrl("http://new.techyardnepal.com");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_favorite) {
startOCRScan();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* start ocr on scan id click
*/
private void startOCRScan() {
// Intent for MyScanActivity
Intent intent = new Intent(this, MRPScanActivity.class);
startActivityForResult(intent, MY_BLINK_ID_REQUEST_CODE);
}
/**
* This method is called whenever control is returned from activity started with
* startActivityForResult.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// onActivityResult is called whenever we are returned from activity started
// with startActivityForResult. We need to check request code to determine
// that we have really returned from BlinkID activity.
if (requestCode == MY_BLINK_ID_REQUEST_CODE) {
if (resultCode == MRPScanActivity.RESULT_OK && data != null) {
// depending on settings, we may have multiple scan results.
// we first need to obtain recognition results
RecognitionResults results = data.getParcelableExtra(ScanActivity.EXTRAS_RECOGNITION_RESULTS);
BaseRecognitionResult[] resArray = null;
if (results != null) {
// get array of recognition results
resArray = results.getRecognitionResults();
}
if (resArray != null) {
Log.i(TAG, "Data count: " + resArray.length);
int i = 1;
for (BaseRecognitionResult res : resArray) {
Log.i(TAG, "Data #" + Integer.valueOf(i++).toString());
// Each element in resultArray inherits BaseRecognitionResult class and
// represents the scan result of one of activated recognizers that have
// been set up.
res.log();
}
} else {
Log.e(TAG, "Unable to retrieve recognition data!");
}
data.setComponent(new ComponentName(this, ResultActivity.class));
startActivity(data);
}
}
if (data != null && data.getBooleanExtra("exit", false))
finish();
if (requestCode == REQUEST_SELECT_FILE) {
if (resultCode != RESULT_OK) {
cancelFileUpload();
return;
}
// from documents (and video camera)
if (data != null && data.getData() != null) {
if (mUploadMessage != null) {
mUploadMessage.onReceiveValue(data.getData());
mUploadMessage = null;
}
return;
}
// we may get clip data for multi-select documents
if (data != null && data.getClipData() != null) {
ClipData clipData = data.getClipData();
ArrayList<Uri> files = new ArrayList<>(clipData.getItemCount());
for (int i = 0; i < clipData.getItemCount(); i++) {
ClipData.Item item = clipData.getItemAt(i);
if (item.getUri() != null) {
files.add(item.getUri());
}
}
if (mUploadMessage != null) {
// shouldn never happen, but just in case, send the first item
if (files.size() > 0) {
mUploadMessage.onReceiveValue(files.get(0));
} else {
mUploadMessage.onReceiveValue(null);
}
mUploadMessage = null;
}
if (uploadMessageLP != null) {
uploadMessageLP.onReceiveValue(files.toArray(new Uri[files.size()]));
uploadMessageLP = null;
}
return;
}
// from camera
if (this.directUploadImageUri != null) {
// check if we have external storage permissions
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSION_READ_EXTERNAL_STORAGE);
// wait for the onRequestPermissionsResult callback
return;
}
if (mUploadMessage != null) {
mUploadMessage.onReceiveValue(this.directUploadImageUri);
mUploadMessage = null;
}
if (uploadMessageLP != null) {
uploadMessageLP.onReceiveValue(new Uri[]{this.directUploadImageUri});
uploadMessageLP = null;
}
this.directUploadImageUri = null;
return;
}
// Should not reach here.
cancelFileUpload();
}
}
}
Try this code:
public class MainActivity extends Activity {
private RelativeLayout mLayout;
private ProgressBar progressBar;
private WebView webView;
String loadUrl;
private static final int INPUT_FILE_REQUEST_CODE = 1;
private static final int FILECHOOSER_RESULTCODE = 1;
private static final String TAG = MainActivity.class.getSimpleName();
private WebSettings webSettings;
private ValueCallback<Uri> mUploadMessage;
private Uri mCapturedImageURI = null;
private ValueCallback<Uri[]> mFilePathCallback;
private String mCameraPhotoPath;
ValueCallback<Uri[]> chooserPathUri;
public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1;
WebView chooserWV;
WebChromeClient.FileChooserParams chooserParams;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadUrl = "https:google.com";
mLayout = (RelativeLayout) findViewById(R.id.activity_main);
progressBar = (ProgressBar)findViewById(R.id.indicator);
webView = (WebView) findViewById(R.id.webView);
webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setDomStorageEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setAllowFileAccess(true);
if (Build.VERSION.SDK_INT >= 19) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}
else if(Build.VERSION.SDK_INT >=11 && Build.VERSION.SDK_INT < 19) {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.setWebChromeClient(new ChromeClient());
webView.loadUrl(loadUrl); //change with your website
this.webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.INVISIBLE);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
}
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return handleUrl(url);
}
#TargetApi(Build.VERSION_CODES.N)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
final Uri uri = request.getUrl();
return handleUrl(request.getUrl().toString());
}
});
}
public boolean handleUrl(String url){
if (url.startsWith("geo:") || url.startsWith("mailto:") || url.startsWith("tel:") || url.startsWith("sms:")) {
Intent searchAddress = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(searchAddress);
}else
webView.loadUrl(url);
return true;
}
private boolean checkAndRequestPermissions() {
int permissionCamera = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
int permissionStorage = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
List<String> listPermissionsNeeded = new ArrayList<>();
if (permissionStorage != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (permissionCamera != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.CAMERA);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS);
Log.e(TAG, "Returned falseeeee-------");
return false;
}
Log.d(TAG, "Permission returned trueeeee-------");
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
Log.d(TAG, "Permission callback called-------");
switch (requestCode) {
case REQUEST_ID_MULTIPLE_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<>();
// Initialize the map with both permissions
perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
// Fill with actual results from user
if (grantResults.length > 0) {
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for both permissions
if (perms.get(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "camera & Storage permission granted");
Toast.makeText(this, "Permissions granted! Try now.", Toast.LENGTH_SHORT).show();
//chromClt.openChooser(chooserWV, chooserPathUri, chooserParams);
// process the normal flow
//else any one or both the permissions are not granted
} else {
Log.d(TAG, "Some permissions are not granted ask again ");
//permission is denied (this is the first time, when "never ask again" is not checked) so ask again explaining the usage of permission
// shouldShowRequestPermissionRationale will return true
//show the dialog or snackbar saying its necessary and try again otherwise proceed with setup.
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
showDialogOK("Camera and Storage Permission required for this app",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
checkAndRequestPermissions();
break;
case DialogInterface.BUTTON_NEGATIVE:
// proceed with logic by disabling the related features or quit the app.
break;
}
}
});
}
//permission is denied (and never ask again is checked)
//shouldShowRequestPermissionRationale will return false
else {
Toast.makeText(this, "Go to settings and enable permissions", Toast.LENGTH_LONG).show();
// //proceed with logic by disabling the related features or quit the app.
}
}
}
break;
}
}
}
private void showDialogOK(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", okListener)
.create()
.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
Uri[] results = null;
// Check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
String dataString = data.getDataString();
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}else {
if (Build.VERSION.SDK_INT >= 16) {
if (data.getClipData() != null) {
final int numSelectedFiles = data.getClipData().getItemCount();
results = new Uri[numSelectedFiles];
for (int i = 0; i < numSelectedFiles; i++) {
results[i] = data.getClipData().getItemAt(i).getUri();
}
}
}
}
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
} else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
if (requestCode != FILECHOOSER_RESULTCODE || mUploadMessage == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
Uri result = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "activity :" + e,
Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
return;
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return imageFile;
}
public class ChromeClient extends WebChromeClient {
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
// callback.invoke(String origin, boolean allow, boolean remember);
Log.e(TAG, "onGeolocationPermissionsShowPrompt: " );
callback.invoke(origin, true, false);
}
// For Android 5.0
public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
chooserWV = view;
chooserPathUri = filePath;
chooserParams = fileChooserParams;
if(checkAndRequestPermissions()){
openChooser(chooserWV, chooserPathUri, chooserParams);
return true;
}else {
return false;
}
}
public void openChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams){
// Double check that we don't have any existing callbacks
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePath;
Intent takePictureIntent;
takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
Log.e(TAG, "Unable to create Image File", ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
if (Build.VERSION.SDK_INT >= 18) {
contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
contentSelectionIntent.setType("*/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
}
// openFileChooser for Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
// Create AndroidExampleFolder at sdcard
// Create AndroidExampleFolder at sdcard
File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES)
, "AndroidExampleFolder");
if (!imageStorageDir.exists()) {
// Create AndroidExampleFolder at sdcard
imageStorageDir.mkdirs();
}
// Create camera captured image file path and name
File file = new File(
imageStorageDir + File.separator + "IMG_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg");
mCapturedImageURI = Uri.fromFile(file);
// Camera capture image intent
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
// Create file chooser intent
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
// Set camera intent to file chooser
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{captureIntent});
// On select image call onActivityResult method of activity
chooserIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}
// openFileChooser for Android < 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
openFileChooser(uploadMsg, "");
}
//openFileChooser for other Android versions
public void openFileChooser(ValueCallback<Uri> uploadMsg,
String acceptType,
String capture) {
openFileChooser(uploadMsg, acceptType);
}
}
#SuppressLint("NewApi")
#Override
protected void onResume() {
super.onResume();
webView.onResume();
// ...
}
#SuppressLint("NewApi")
#Override
protected void onPause() {
webView.onPause();
// ...
super.onPause();
}
int mExit = 0;
#Override
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
Don't forget to add permissions in Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>

Is disappearing after going to another activity but showing uploading to server Glide and volley

I have created two functionality for photo uploading in my app. The first one is for capture image and the second one is for pick image from gallery. Now I have a photo API as URL. By using this API I have to upload the image at first to server and from server it will be available throught the app. Now I can successfully uploaded the picture in server and in the server side shows the picture. But in the imageview of app does not show that image. Whenever I go to another activity and then come back to image activity the imageview is empty. I have used shared preference to keep the image at image view, but that does not work.
Here is my code for photo activity
public class ViewProfileFragment extends Fragment implements
View.OnClickListener{
private static final int CODE_GALLERY_REQUEST =999 ;
private static final int MY_CAMERA_REQUEST_CODE = 100;
private ImageView image;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private String userChoosenTask;
Bitmap bm;
private String UPLOAD_URL = Constants.HTTP.PHOTO_URL;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_view_profile,
container, false);
.........
image=(ImageView)rootView.findViewById(R.id.profile_pic);
saveData();
return rootView;
}
public void saveData(){
Log.d( "----ViewProfile-Email", "mEmail" );
GlobalClass globalClass = new GlobalClass();
String mEmail = globalClass.getEmail_info();
Realm profileRealm;
profileRealm = Realm.getDefaultInstance();
RealmResults<MyColleagueModel> results =
profileRealm.where(MyColleagueModel.class).equalTo("mail",
mEmail).findAll();
//fetching the data
results.load();
if (results.size() > 0) {
......
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(getActivity());
String mImageUri = preferences.getString("image", null);
if (mImageUri != null) {
image.setImageURI(Uri.parse(mImageUri));
} else {
Glide.with( this )
.load(Constants.HTTP.PHOTO_URL+mail)
.thumbnail(0.5f)
.override(200,200)
.diskCacheStrategy( DiskCacheStrategy.ALL)
.into( image);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[]
permissions, int[] grantResults) {
if(requestCode==CODE_GALLERY_REQUEST){
if(grantResults.length>0 && grantResults[0]==
PackageManager.PERMISSION_GRANTED){
galleryIntent();
}
else {
Toast.makeText( getActivity().getApplicationContext(),"You
don't have permission to access gallery",Toast.LENGTH_LONG ).show();
}
return;
}
if(requestCode==MY_CAMERA_REQUEST_CODE){
if(grantResults.length>0 && grantResults[0]==
PackageManager.PERMISSION_GRANTED){
cameraIntent();
}
else {
Toast.makeText( getActivity().getApplicationContext(),"You
don't have permission to access gallery",Toast.LENGTH_LONG ).show();
}
return;
}
super.onRequestPermissionsResult( requestCode, permissions,grantResults );
}
public void showDialog(){
//Create a new builder and get the layout.
final AlertDialog.Builder builder = new
AlertDialog.Builder(this.getActivity());
.....
}
});
alertListView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListViekw Clicked item index
if (position == 0) {
userChoosenTask ="Take Photo";
alert.dismiss();
if(isPermissionGrantedCamera()) {
cameraIntent();
}
}
else if (position == 1){
userChoosenTask ="Choose from Library";
alert.dismiss();
if(isPermissionGrantedGallery()) {
galleryIntent();
}
}
}
});
}
public boolean isPermissionGrantedGallery() {
if (Build.VERSION.SDK_INT >= 23) {
if
(getActivity().checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v("TAG","Permission is granted");
return true;
} else {
Log.v("TAG","Permission is revoked");
ActivityCompat.requestPermissions(this.getActivity(), new
String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon
installation
Log.v("TAG","Permission is granted");
return true;
}
}
public boolean isPermissionGrantedCamera() {
if (Build.VERSION.SDK_INT >= 23) {
if
(getActivity().checkSelfPermission(android.Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED) {
Log.v("TAG","Permission is granted");
return true;
} else {
Log.v("TAG","Permission is revoked");
ActivityCompat.requestPermissions(this.getActivity(), new
String[]{Manifest.permission.CAMERA}, 0);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon
installation
Log.v("TAG","Permission is granted");
return true;
}
}
private void galleryIntent()
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select
File"),SELECT_FILE);
}
public void cameraIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if
(takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null)
{
File cameraFolder;
if
(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
cameraFolder = new
File(Environment.getExternalStorageDirectory(), "image/");
} else {
cameraFolder = getActivity().getCacheDir();
}
if (!cameraFolder.exists()) {
cameraFolder.mkdirs();
}
String imageFileName = System.currentTimeMillis() + ".jpg";File photoFile = new File(cameraFolder + imageFileName);
currentPhotoPath = photoFile.getAbsolutePath();
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_CAMERA);
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_FILE && data!=null){
onSelectFromGalleryResult(data);
}
else if (requestCode == REQUEST_CAMERA ) {
if(!TextUtils.isEmpty(currentPhotoPath)) {
try {
galleryAddPic();
onCaptureImageResult();
}
catch (Exception e){
}
}
}
}
}
private void galleryAddPic() {
Intent mediaScanIntent = new
Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.getActivity().sendBroadcast(mediaScanIntent);
}
private void onCaptureImageResult() {
Bitmap bitmap = getBitmapFromPath(currentPhotoPath, 200, 200);
image.setImageBitmap(bitmap);
compressBitMap(bitmap);
}
private void onSelectFromGalleryResult(Intent data) {
Uri uri = data.getData();
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContext().getContentResolver().query(uri,
projection, null, null, null);
if (cursor != null) {
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
currentPhotoPath = cursor.getString(column_index);
cursor.close();
} else {
currentPhotoPath = uri.getPath();
}// Saves image URI as string to Default Shared Preferences
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("image", String.valueOf(uri));
editor.commit();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
bm = BitmapFactory.decodeFile(currentPhotoPath);
compressBitMap(bm);
}
private void compressBitMap(Bitmap bitmap) {
ImageConversion imageConversion = new ImageConversion();
byte[] bytesArray;
int maxSize = 10 * 1024;
int imageMaxQuality = 50;
int imageMinQuality = 5;
bytesArray = imageConversion.convertBitmapToByteArray(bitmap,
imageMaxQuality, imageMinQuality, maxSize);
File destination = new
File(getContext().getApplicationContext().getFilesDir(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytesArray);
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
currentPhotoPath = destination.getPath();
uploadImage(bytesArray);
}
private void uploadImage(final byte[] bytesArray){
.....
}
}
Please don't use
image.setImageURI(uri);
image.invalidate();
Please use this code below instead of that :
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}

How to get image from gallery in android marshmallow?

Hi i am working in app were user can select image when he is registering an account. I am able to get image on lollipop but when i am testing it in marshmallow then i am not getting file and its name, I am able to ask permission from user and when i am selecting image from gallery i am not getting any file or its name
This is my Code
select_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Build.VERSION.SDK_INT >=23) {
if (checkPermission()){
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}else{
requestPermission();
}
}else{
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
}
});
My Permissions
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(Register.this, Manifest.permission.READ_EXTERNAL_STORAGE );
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(Register.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
Toast.makeText(Register.this, "Write External Storage permission allows us to access images. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(Register.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
if(requestCode == PERMISSION_REQUEST_CODE){
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Accepted", Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
} else {
Log.e("value", "Permission Denied, You cannot use local drive .");
}
}
}
After Selecting Image
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
filePath = data.getData();
if (null != filePath) {
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), filePath);
// img.setImageBitmap(bitmap);
if (filePath.getScheme().equals("content")) {
try (Cursor cursor = getContentResolver().query(filePath, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
file_name = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
Toast.makeText(this, file_name, Toast.LENGTH_SHORT).show();
img_name.setText(file_name);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
I am not getting why its not working in marshmallow even i have given permissions
I solved it.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
filePath = data.getData();
if (null != filePath) {
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), filePath);
// img.setImageBitmap(bitmap);
if (filePath.getScheme().equals("content")) {
try (Cursor cursor = getContentResolver().query(filePath, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
file_name = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
Toast.makeText(this, file_name, Toast.LENGTH_SHORT).show();
img_name.setText(file_name);
}
}
}else {
String path= data.getData().getPath();
file_name=path.substring(path.lastIndexOf("/")+1);
img_name.setText(file_name);
Toast.makeText(this, file_name, Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
When i was selecting file , then i was not going to this condition
if (filePath.getScheme().equals("content"))
so in else condition i have given this
String path= data.getData().getPath();
file_name=path.substring(path.lastIndexOf("/")+1);
img_name.setText(file_name);
Toast.makeText(this, file_name, Toast.LENGTH_SHORT).show();
To get image from gallery on any api level then follow this :
Copy and paste all 4 function to your activity
And call this to open gallery galleryPermissionDialog();
Variable used
final private int REQUEST_CODE_ASK_PERMISSIONS = 123;
protected static final int REQUEST_CODE_MANUAL = 5;
Permission need to add for lower than marshmallow
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Function 1:
void openGallry() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
}
Function 2 :
void galleryPermissionDialog() {
int hasWriteContactsPermission = ContextCompat.checkSelfPermission(ActivityProfile.this,
android.Manifest.permission.READ_EXTERNAL_STORAGE);
if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(ActivityProfile.this,
new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_ASK_PERMISSIONS);
return;
} else {
openGallry();
}
}
Function 3 :
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<String, Integer>();
// Initial
perms.put(android.Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
// Fill with results
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for READ_EXTERNAL_STORAGE
boolean showRationale = false;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
if (perms.get(android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
// All Permissions Granted
galleryPermissionDialog();
} else {
showRationale = ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_EXTERNAL_STORAGE);
if (showRationale) {
showMessageOKCancel("Read Storage Permission required for this app ",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
galleryPermissionDialog();
}
});
} else {
showMessageOKCancel("Read Storage Permission required for this app ",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(ActivityProfile.this, "Please Enable the Read Storage permission in permission", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, REQUEST_CODE_MANUAL);
}
});
//proceed with logic by disabling the related features or quit the app.
}
}
} else {
galleryPermissionDialog();
}
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
Function 4 :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
try {
final Uri imageUri = imageReturnedIntent.getData();
/* final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
img_profile.setImageBitmap(selectedImage);*/
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(imageUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
pictureFile = saveBitmapToFile(new File(picturePath));
Picasso.with(getApplicationContext()).load(new File(picturePath)).transform(new CircleTransform()).into(imgProfile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Function 5 :
public void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(ActivityProfile.this)
.setTitle(R.string.app_name)
.setMessage(message)
.setCancelable(false)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
file/* is not a valid MIME type. You should use / if you want to support any type of file. The files you see are unselectable because they are not of the correct MIME type.
With the introduction of virtual files in Android 7.0 (files that don't have a bytestream and therefore cannot be directly uploaded), you should most definitely add CATEGORY_OPENABLE to your Intent:
https://developer.android.com/about/versions/nougat/android-7.0.html#virtual_files
https://developer.android.com/reference/android/content/Intent.html#CATEGORY_OPENABLE
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//sets the select file to all types of files
intent.setType("*/*");
// Only get openable files
intent.addCategory(Intent.CATEGORY_OPENABLE);
//starts new activity to select file and return data
startActivityForResult(Intent.createChooser(intent,
"Choose File to Upload.."), PICK_FILE_REQUEST);
}
public String getFileName(Uri uri) {
String result = null;
if (uri.getScheme().equals("content")) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
}
if (result == null) {
result = uri.getPath();
int cut = result.lastIndexOf('/');
if (cut != -1) {
result = result.substring(cut + 1);
}
}
return result;
}
String filename =getFileName(yourfileuri);

Activity associated with image cropping libraries does not destroy

I have tried to solve this problem from many different links but does not worked for me.I am using Android Image Cropper library for cropping images. Whenever i click on the button "upload image" it start the cropping activity and when i am done the cropped image is set in an imageview in "upload image" activity and after clicking "Proceed" button login is successful and i am directed to login activity but when i back press the login activity the "Upload image" activity is still there and is not destroyed. I have another activity called Update Activity that uses this Cropping activity and that activity also behaves in the same manner. So i want the "Upload image" to destroy. Thanks in advance
package com.donateblood.blooddonation;
public class CroppingActivity extends AppCompatActivity {
private CropImageView mCropImageView;
public static Bitmap finalImage = null;
public static Bitmap newImage = null;
private Uri mCropImageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crop);
mCropImageView = (CropImageView) findViewById(R.id.CropImageView);
}
/**
* On load image button click, start pick image chooser activity.
*/
public void onLoadImageClick(View view) {
startActivityForResult(getPickImageChooserIntent(), 200);
}
public void onSetImageClick(View view) {
if(UpdateActivity.UpdatingPhoto){
newImage = mCropImageView.getCroppedImage(200, 200);
try {
Intent intent = new Intent(getApplicationContext(), UpdateActivity.class);
startActivity(intent);
finish();
} catch (Exception e) {
Toast.makeText(CroppingActivity.this, "Oppss..Error occured.", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}else {
finalImage = mCropImageView.getCroppedImage(200, 200);
try {
Intent intent = new Intent(getApplicationContext(), UploadImage.class);
startActivity(intent);
finish();
} catch (Exception e) {
Toast.makeText(CroppingActivity.this, "Oppss..Error occured.", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
/**
* Crop the image and set it back to the cropping view.
*/
public void onCropImageClick(View view) {
Bitmap cropped = mCropImageView.getCroppedImage(500, 500);
if (cropped != null)
mCropImageView.setImageBitmap(cropped);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
Uri imageUri = getPickImageResultUri(data);
// For API >= 23 we need to check specifically that we have permissions to read external storage,
// but we don't know if we need to for the URI so the simplest is to try open the stream and see if we get error.
boolean requirePermissions = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED &&
isUriRequiresPermissions(imageUri)) {
// request permissions and handle the result in onRequestPermissionsResult()
requirePermissions = true;
mCropImageUri = imageUri;
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
if (!requirePermissions) {
mCropImageView.setImageUriAsync(imageUri);
}
}
}
#Override
public void onBackPressed() {
UpdateActivity.UpdatingPhoto = false;
super.onBackPressed();
finish();
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (mCropImageUri != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mCropImageView.setImageUriAsync(mCropImageUri);
} else {
Toast.makeText(this, "Required permissions are not granted", Toast.LENGTH_LONG).show();
}
}
/**
* Create a chooser intent to select the source to get image from.<br/>
* The source can be camera's (ACTION_IMAGE_CAPTURE) or gallery's (ACTION_GET_CONTENT).<br/>
* All possible sources are added to the intent chooser.
*/
public Intent getPickImageChooserIntent() {
// Determine Uri of camera image to save.
Uri outputFileUri = getCaptureImageOutputUri();
List<Intent> allIntents = new ArrayList<>();
PackageManager packageManager = getPackageManager();
// collect all camera intents
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam) {
Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(res.activityInfo.packageName);
if (outputFileUri != null) {
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
}
allIntents.add(intent);
}
// collect all gallery intents
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
List<ResolveInfo> listGallery = packageManager.queryIntentActivities(galleryIntent, 0);
for (ResolveInfo res : listGallery) {
Intent intent = new Intent(galleryIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(res.activityInfo.packageName);
allIntents.add(intent);
}
// the main intent is the last in the list (Foolish android) so pickup the useless one
Intent mainIntent = allIntents.get(allIntents.size() - 1);
for (Intent intent : allIntents) {
if (intent.getComponent().getClassName().equals("com.android.documentsui.DocumentsActivity")) {
mainIntent = intent;
break;
}
}
allIntents.remove(mainIntent);
// Create a chooser from the main intent
Intent chooserIntent = Intent.createChooser(mainIntent, "Select source");
// Add all other intents
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, allIntents.toArray(new Parcelable[allIntents.size()]));
return chooserIntent;
}
/**
* Get URI to image received from capture by camera.
*/
private Uri getCaptureImageOutputUri() {
Uri outputFileUri = null;
File getImage = getExternalCacheDir();
if (getImage != null) {
outputFileUri = Uri.fromFile(new File(getImage.getPath(), "pickImageResult.jpeg"));
}
return outputFileUri;
}
/**
* Get the URI of the selected image from {#link #getPickImageChooserIntent()}.<br/>
* Will return the correct URI for camera and gallery image.
*
* #param data the returned data of the activity result
*/
public Uri getPickImageResultUri(Intent data) {
boolean isCamera = true;
if (data != null && data.getData() != null) {
String action = data.getAction();
isCamera = action != null && action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
}
return isCamera ? getCaptureImageOutputUri() : data.getData();
}
/**
* Test if we can open the given Android URI to test if permission required error is thrown.<br>
*/
public boolean isUriRequiresPermissions(Uri uri) {
try {
ContentResolver resolver = getContentResolver();
InputStream stream = resolver.openInputStream(uri);
stream.close();
return false;
} catch (FileNotFoundException e) {
if (e.getCause() instanceof ErrnoException) {
return true;
}
} catch (Exception e) {
}
return false;
}
}
package com.donateblood.blooddonation;
public double longitude;
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.uploadimage);
code = (EditText) findViewById(R.id.code);
ButterKnife.inject(this);
myimage = CroppingActivity.finalImage;
CheckImage();
// Upload image ====================================
Btn_Upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), CroppingActivity.class);
startActivity(intent);
}
});
Btn_Proceed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(code.length()==0){
Toast.makeText(getBaseContext(), "Enter verification code", Toast.LENGTH_LONG).show();
}
else {
Prcoess();
}
}
});
}
public void CheckImage(){
if(myimage!=null){
// set the image
// myimage = getRoundedShape(myimage);
Uri uri = getImageUri(myimage);
String url = getRealPathFromURI(uri);
File file = new File(url);
Picasso.with(UploadImage.this).load(file).resize(200,200).placeholder(R.drawable.user).error(R.drawable.error)
.transform(new CircleTransform()).centerCrop()
.into(ImageUpload);
}else {
encodedPhotoString= null;
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public String getRealPathFromURI(Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = UploadImage.this.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public Uri getImageUri( Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(UploadImage.this.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
// Processing and adding user to database from here ====================================
public void Prcoess(){
String userentered=code.getText().toString();
String sentcode = SignupActivity.Code;
// resize the image to store to database
//myimage= getResizedBitmap(myimage,200,200);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myimage.compress(Bitmap.CompressFormat.JPEG, 50, stream);
byte[] byte_arr = stream.toByteArray();
encodedPhotoString = Base64.encodeToString(byte_arr, 0);
if(userentered.equals(sentcode) && encodedPhotoString!=null ){
new AddUserAsync().execute();
}
else {
Toast.makeText(getBaseContext(), "Wrong code or No image uploaded", Toast.LENGTH_LONG).show();
}
}
public class AddUserAsync extends AsyncTask<Void,Void,Void> {
JSONObject json =null;
boolean added = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UploadImage.this);
pDialog.setMessage("Creating Account...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
GetUserDetails();
GenerateGCMID();
email= email.trim().toLowerCase();
HashMap<String ,String> userDetails = new HashMap<>();
latitude = GPSTracker.getLatitude();
longitude = GPSTracker.getLongitude();
userDetails.put("ID",ID);
userDetails.put("Name",name);
userDetails.put("email",email);
userDetails.put("password",password);
userDetails.put("age",age);
userDetails.put("number",number);
userDetails.put("bloodgroup",bloodgroup);
userDetails.put("lat",latitude+"");
userDetails.put("longi",longitude+"");
userDetails.put("image",encodedPhotoString);
json = new HttpCall().postForJSON("http://abdulbasit.website/blood_app/Adduser.php",userDetails);
if(json!=null){
added = true;
}else {
added = false;
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pDialog.dismiss();
if(added==true){
Toast.makeText(getBaseContext(), "Created Successfully", Toast.LENGTH_LONG).show();
onSignupSuccess();
}else {
Toast.makeText(getBaseContext(), "Error creating account. Try again", Toast.LENGTH_LONG).show();
}
}
}
public void GenerateGCMID(){
GCMClientManager pushClientManager = new GCMClientManager(this, "921544902369");
pushClientManager.registerIfNeeded(new GCMClientManager.RegistrationCompletedHandler() {
#Override
public void onSuccess(String registrationId, boolean isNewRegistration) {
Log.d("Registration id", registrationId);
ID = registrationId;
Log.e("reg",ID);
}
#Override
public void onFailure(String ex) {
super.onFailure(ex);
}
});
}
// Go to another activity on success ====================================
public void onSignupSuccess() {
// stop the service we got the latitude and longitude now
stopService(new Intent(this, GPSTracker.class));
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
finish();
}
// fetch user details ====================================
public void GetUserDetails(){
bloodgroup = SignupActivity.bloodgroup.toString();
name = SignupActivity.name.toString();
email = SignupActivity.email.toString();
password = SignupActivity.password.toString();
number = SignupActivity.number.toString();
age = SignupActivity.age.toString();
}
// Resize the image ====================================
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth)
{
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
}
check this method you are not finishing the UploadActivity here:-
Btn_Upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), CroppingActivity.class);
startActivity(intent);
UploadActivity.this.finish();
}
});

Categories

Resources