how to add multiple imageview dynamically - android

im about to make like photo album so we can upload multiple photo (like facebook, etc)
ivAttachment1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(strPhoto1 == "" && PageType.equals("NewRequestMedical")) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);
photoTemp = "photo1";
}
else if(strPhoto1 == "" && !PageType.equals("NewRequestMedical"))
{
Toast.makeText(getApplicationContext(), "there is no attachment on this request",
Toast.LENGTH_SHORT).show();
}else {
Intent i = new Intent(MedicalClaim.this, DetailPhotoMedical.class);
/* i.putExtra("photo", strPhoto1);*/
Bundle extras = new Bundle();
extras.putString("photo", strPhoto1);
extras.putString("photoNo","photo1");
extras.putString("PageTypeRequest",PageType);
i.putExtras(extras);
startActivityForResult(i,100);
//i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
}
});
ivAttachment2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(strPhoto2 == "" && PageType.equals("NewRequestMedical")) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);
photoTemp = "photo2";
}
else if(strPhoto2 == "" && !PageType.equals("NewRequestMedical"))
{
Toast.makeText(getApplicationContext(), "there is no attachment on this request",
Toast.LENGTH_SHORT).show();
}
else
{
Intent i = new Intent(MedicalClaim.this, DetailPhotoMedical.class);
/* i.putExtra("photo", strPhoto2);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);*/
Bundle extras = new Bundle();
extras.putString("photo", strPhoto2);
extras.putString("photoNo","photo2");
extras.putString("PageTypeRequest",PageType);
i.putExtras(extras);
startActivityForResult(i,100);
}
}
});
ivAttachment3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(strPhoto3 == "" && PageType.equals("NewRequestMedical")) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);
photoTemp = "photo3";
}
else if(strPhoto3 == "" && !PageType.equals("NewRequestMedical"))
{
Toast.makeText(getApplicationContext(), "there is no attachment on this request",
Toast.LENGTH_SHORT).show();
}else
{
Intent i = new Intent(MedicalClaim.this, DetailPhotoMedical.class);
Bundle extras = new Bundle();
extras.putString("photo", strPhoto3);
extras.putString("photoNo","photo3");
extras.putString("PageTypeRequest",PageType);
i.putExtras(extras);
startActivityForResult(i,100);
/*i.putExtra("photo", strPhoto3);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);*/
}
}
});
ivAttachment4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(strPhoto4 == "" && PageType.equals("NewRequestMedical")) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);
photoTemp = "photo4";
}
else if(strPhoto4 == "" && !PageType.equals("NewRequestMedical"))
{
Toast.makeText(getApplicationContext(), "there is no attachment on this request",
Toast.LENGTH_SHORT).show();
}else
{
Intent i = new Intent(MedicalClaim.this, DetailPhotoMedical.class);
Bundle extras = new Bundle();
extras.putString("photo", strPhoto4);
extras.putString("photoNo","photo4");
extras.putString("PageTypeRequest",PageType);
i.putExtras(extras);
startActivityForResult(i,100);
/* i.putExtra("photo", strPhoto4);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);*/
}
}
});
ivAttachment5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(strPhoto5 == "" && PageType.equals("NewRequestMedical")) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);
photoTemp = "photo5";
}
else if(strPhoto5 == "" && !PageType.equals("NewRequestMedical"))
{
Toast.makeText(getApplicationContext(), "there is no attachment on this request",
Toast.LENGTH_SHORT).show();
}
else{
Intent i = new Intent(MedicalClaim.this, DetailPhotoMedical.class);
Bundle extras = new Bundle();
extras.putString("photo", strPhoto5);
extras.putString("photoNo","photo5");
extras.putString("PageTypeRequest",PageType);
i.putExtras(extras);
startActivityForResult(i,100);
/* i.putExtra("photo", strPhoto5);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);*/
}
}
});
now i just make 10 imageviews and declare all. which is not dynamic. and i convert the photo to bitmap and it will be send to database.
is there any way or library that i can use?

You can have a "Add Image" button like below instead of having multiple images.
Then on "add image" button click you can hit gallery intent with startactivityforresults() for getting the images and onAcivityResult() you can create imageView and add it to container and upload the same.
public void addImageView(Context context, View container){
ImageView imgNew = new ImageView(context);
//add layout params & set image
container.addView(newImage);
// start service to upload the image
}

Related

Getting an image from gallery and camera (Android Studio)

I am working on an project where the user can change their profile picture either by taking a picture or selecting an image from Gallery. Despite following multiple tutorials, the code they use does not work for me. Whenever I select Camera on the Dialog Box, it goes to Gallery then Camera. Likewise when I select Gallery on the Dialog Box, it does go to Gallery but it will still go to Camera before displaying the image on the Image View. Is it because I am using Android Lollipop? I am not really sure too.
How can I get this fixed?
package com.example.user.imagestuff;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
String[] Items;
ImageView mImageView;
Button mButton;
final int bmpHeight = 160;
final int bmpWidth = 160;
static final int CAMERA_CODE = 1;
static final int GALLERY_CODE = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = (ImageView) findViewById(R.id.mImageView);
mButton = (Button) findViewById(R.id.mButton);
Items = getResources().getStringArray(R.array.DialogItems);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ImageOnClick(v);
}
});
}
public void ImageOnClick(View v) {
Log.i("OnClick","True");
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.AlertTitle);
builder.setItems(Items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for(int i=0; i < Items.length; i++){
if (Items[i].equals("Camera")){
Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if(CameraIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(CameraIntent, CAMERA_CODE);
}
}else if (Items[i].equals("Gallery")){
Log.i("GalleryCode",""+GALLERY_CODE);
Intent GalleryIntent = null;
GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
GalleryIntent.setType("image/*");
GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(GalleryIntent,GALLERY_CODE);
}
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK){
switch(requestCode){
case 1:
Log.i("CameraCode",""+CAMERA_CODE);
Bundle bundle = data.getExtras();
Bitmap bmp = (Bitmap) bundle.get("data");
Bitmap resized = Bitmap.createScaledBitmap(bmp, bmpWidth,bmpHeight, true);
mImageView.setImageBitmap(resized);
case 0:
Log.i("GalleryCode",""+requestCode);
Uri ImageURI = data.getData();
mImageView.setImageURI(ImageURI);
}
}
}
}
Because you are using for loop for checking Camera and Gallary Strings. You need to remove for loop and try ike below code
And also you missing break in your swith case
final CharSequence[] items = {"Camera", "Gallery"}
if (items[item].equals("Camera")){
Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if(CameraIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(CameraIntent, CAMERA_CODE);
}
}else if (items[item].equals("Gallery")){
Log.i("GalleryCode",""+GALLERY_CODE);
Intent GalleryIntent = null;
GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
GalleryIntent.setType("image/*");
GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(GalleryIntent,GALLERY_CODE);
}
Second Option
You can also put break; keyword for breaking your for loop when your condition match
You are opening an intent in for loop and there is another mistake is you are not breaking the case in your switch case. Use break in your switch case
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK){
switch(requestCode){
case 1:
Log.i("CameraCode",""+CAMERA_CODE);
Bundle bundle = data.getExtras();
Bitmap bmp = (Bitmap) bundle.get("data");
Bitmap resized = Bitmap.createScaledBitmap(bmp, bmpWidth,bmpHeight, true);
mImageView.setImageBitmap(resized);
break;
case 0:
Log.i("GalleryCode",""+requestCode);
Uri ImageURI = data.getData();
mImageView.setImageURI(ImageURI);
break;
}
}
This works fine for me.
public static final int CAMERA_PERMISSION =100;
public static final int REQUEST_IMAGE_CAPTURE =101;
public static final int READ_STORAGE_PERMISSION =102;
public static final int REQUEST_IMAGE_PICK =103 ;
private Dialog mCameraDialog;
private Uri mImageURI;
/**
* Method to show list dialog to choose photo form gallery or camera.
*/
private void showChoosePhotoDialog() {
mCameraDialog.setContentView(R.layout.dialog_choose_photo);
if(mCameraDialog.getWindow()!=null)
mCameraDialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
mCameraDialog.findViewById(R.id.camera).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCameraDialog.dismiss();
onCameraOptionSelected();
}
});
mCameraDialog.findViewById(R.id.gallery).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCameraDialog.dismiss();
onGalleryOptionSelected();
}
});
mCameraDialog.show();
}
/**
* Method to open gallery.
*/
private void onGalleryOptionSelected() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Intent intentGallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intentGallery, REQUEST_IMAGE_PICK);
overridePendingTransition(R.anim.push_left_right, R.anim.push_right_left);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
READ_STORAGE_PERMISSION);
}
}
/**
* Method to open chooser.
*/
private void onCameraOptionSelected() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
CAMERA_PERMISSION);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION);
}
} else if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
CAMERA_PERMISSION);
} else {
mImageURI = Uri.parse(AppUtils.getFilename());
startActivityForResult(AppUtils.getCameraChooserIntent(EditProfileActivity.this, mImageURI + ""),
REQUEST_IMAGE_CAPTURE);
}
} else {
mImageURI = Uri.parse(AppUtils.getFilename());
startActivityForResult(AppUtils.getCameraChooserIntent(this, mImageURI + ""),
REQUEST_IMAGE_CAPTURE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case CAMERA_PERMISSION:
int j = 0;
for (int grantResult : grantResults) {
if (grantResult != PackageManager.PERMISSION_GRANTED)
j = 1;
}
if (j == 1) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) || (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA))) {
// Toast.makeText(this, R.string.s_camera_permission, Toast.LENGTH_SHORT).show();
} else if (!ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) || !ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
// Open phone settings page.
// Toast.makeText(this, getString(R.string.s_app_needs_camera_permission), Toast.LENGTH_SHORT).show();
}
} else
onCameraOptionSelected();
break;
case READ_STORAGE_PERMISSION:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
onGalleryOptionSelected();
else if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Toast.makeText(this, getString(R.string.s_storage_permission), Toast.LENGTH_SHORT).show();
} else if (!ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Open Phone Settings
}
}
}
Please Replace your code
public void ImageOnClick(View v) {
Log.i("OnClick","True");
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.AlertTitle);
builder.setItems(Items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for(int i=0; i < Items.length; i++){
if (Items[i].equals("Camera")){
Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if(CameraIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(CameraIntent, CAMERA_CODE);
}
}else if (Items[i].equals("Gallery")){
Log.i("GalleryCode",""+GALLERY_CODE);
Intent GalleryIntent = null;
GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
GalleryIntent.setType("image/*");
GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(GalleryIntent,GALLERY_CODE);
}
}
}
});
builder.show();
}
To
public void ImageOnClick(View v) {
Log.i("OnClick","True");
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.AlertTitle);
builder.setItems(Items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Items[which].equals("Camera")){
Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if(CameraIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(CameraIntent, CAMERA_CODE);
}
}else if (Items[which].equals("Gallery")){
Log.i("GalleryCode",""+GALLERY_CODE);
Intent GalleryIntent = null;
GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
GalleryIntent.setType("image/*");
GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(GalleryIntent,GALLERY_CODE);
}
}
});
builder.show();
}
you didnt use break statement thats why its moving to next statement.
just use break statement when you are firing an intent
public void ImageOnClick (View v){
Log.i("OnClick", "True");
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.AlertTitle);
builder.setItems(Items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for (int i = 0; i < Items.length; i++) {
if (Items[i].equals("Camera")) {
Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if (CameraIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(CameraIntent, CAMERA_CODE);
}
break;
} else if (Items[i].equals("Gallery")) {
Log.i("GalleryCode", "" + GALLERY_CODE);
Intent GalleryIntent = null;
GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
GalleryIntent.setType("image/*");
GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(GalleryIntent, GALLERY_CODE);
}
break;
}
}
});
builder.show();
}
To make it efficient use position value, when you set onclickListener it returns one int variable which is position of list which is clicked. In your case its int which So you can simply use
public void ImageOnClick (View v){
Log.i("OnClick", "True");
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.AlertTitle);
builder.setItems(Items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Items[which].equals("Camera")) {
Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if (CameraIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(CameraIntent, CAMERA_CODE);
}
break;
} else if (Items[which].equals("Gallery")) {
Log.i("GalleryCode", "" + GALLERY_CODE);
Intent GalleryIntent = null;
GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
GalleryIntent.setType("image/*");
GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(GalleryIntent, GALLERY_CODE);
}
break;
}
});
builder.show();
}
Also in OnActivityResult method use break statement otherwise it will both cases
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case 1:
Log.i("CameraCode", "" + CAMERA_CODE);
Bundle bundle = data.getExtras();
Bitmap bmp = (Bitmap) bundle.get("data");
Bitmap resized = Bitmap.createScaledBitmap(bmp, bmpWidth, bmpHeight, true);
mImageView.setImageBitmap(resized);
break;
case 0:
Log.i("GalleryCode", "" + requestCode);
Uri ImageURI = data.getData();
mImageView.setImageURI(ImageURI);
break;
}
}
}

Camera and gallery crop options

I am using camera option in my app but it works some devices only. Also I need crop options.
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_CODE && resultCode == RESULT_OK && null != data) {
mImageCaptureUri = data.getData();
System.out.println("Gallery Image URI : "+mImageCaptureUri);
CropingIMG();
}
}
To fix camera issue, I have used following methods
CameraIntentHelper
onSaveInstanceState
onRestoreInstanceState
onActivityResult
private void selectImage() {
final CharSequence[] options = {"Take Photo", "Choose from Gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(PhotoSuiteActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
if (mCameraIntentHelper != null) {
mCameraIntentHelper.startCameraIntent();
} else {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String imageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/picture.png";
File imageFile = new File(imageFilePath);
picUri = Uri.fromFile(imageFile); // convert path to Uri
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
startActivityForResult(takePictureIntent, CAMERA_CAPTURE);
}
} else if (options[item].equals("Choose from Gallery")) {
Toast.makeText(PhotoSuiteActivity.this, "Not yet Ready...!", Toast.LENGTH_SHORT).show();
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void setupCameraIntentHelper() {
mCameraIntentHelper = new CameraIntentHelper(this, new CameraIntentHelperCallback() {
#Override
public void onPhotoUriFound(Date dateCameraIntentStarted, Uri photoUri, int rotateXDegrees) {
messageView.setText(getString(R.string.activity_camera_intent_photo_uri_found) + photoUri.toString());
mImageCaptureUri = photoUri;
Bitmap photo = BitmapHelper.readBitmap(PhotoSuiteActivity.this, photoUri);
if (photo != null) {
photo = BitmapHelper.shrinkBitmap(photo, 300, rotateXDegrees);
imageView.setImageBitmap(photo);
CropingIMG();
}
}
#Override
public void deletePhotoWithUri(Uri photoUri) {
BitmapHelper.deleteImageWithUriIfExists(photoUri, PhotoSuiteActivity.this);
}
#Override
public void onSdCardNotMounted() {
Toast.makeText(getApplicationContext(), getString(R.string.error_sd_card_not_mounted), Toast.LENGTH_LONG).show();
}
#Override
public void onCanceled() {
Toast.makeText(getApplicationContext(), getString(R.string.warning_camera_intent_canceled), Toast.LENGTH_LONG).show();
}
#Override
public void onCouldNotTakePhoto() {
Toast.makeText(getApplicationContext(), getString(R.string.error_could_not_take_photo), Toast.LENGTH_LONG).show();
}
#Override
public void onPhotoUriNotFound() {
messageView.setText(getString(R.string.activity_camera_intent_photo_uri_not_found));
}
#Override
public void logException(Exception e) {
Toast.makeText(getApplicationContext(), getString(R.string.error_sth_went_wrong), Toast.LENGTH_LONG).show();
Log.d(getClass().getName(), e.getMessage());
}
});
}

Return to MainActivity from another activity with error message

I am a bit new in android and I want to return to main activity from current activity with error message in dialog box.
I have written a script which make a call to rest api and if there is no data or error from response then i want to return to main activity with that error in dialog box.
Here is what i am doing
txtScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
private void selectImage(){
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
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 (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
byte[] b;
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
String fileName = File.separator + System.currentTimeMillis() + ".jpg";
filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + fileName;
System.out.println(filePath);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
/*FileInputStream fis = null;
try{
fis = new FileInputStream(filePath);
}catch (FileNotFoundException e){
e.printStackTrace();
}*/
b = bytes.toByteArray();
encode_string = Base64.encodeToString(b, Base64.DEFAULT);
System.out.println(b);
System.out.println(encode_string);
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();
}
try{
obj = new JSONObject();
obj.put("image",encode_string);
obj.put("api_key",API_SECRET);
System.out.println(obj.toString());
}catch (Throwable t){
t.printStackTrace();
}
new Image().execute();
//new LongRunningGetIO().execute();
//ivImage.setImageBitmap(thumbnail);
}
This function is In Image class
#Override
protected void onPostExecute(Void r) {
progressDialog.dismiss();
if(responseBody == "Api key does not found/match"){
//here i want to return to main activity with error
}else {
byte[] imageAsBytes = Base64.decode(encode_string.getBytes(), Base64.DEFAULT);
//System.out.println(imageAsBytes);
Intent intent = new Intent(getActivity().getApplicationContext(), ViewActivity.class);
intent.putExtra("filePath", imageAsBytes);
//intent.putExtra("data", text);
startActivity(intent);
}
}
Any idea thanks in advance
use startActivityForResults for passing value from current activity to previous activity
call Activity
Intent intent=new Intent(MainActivity.this,CurrentActivity.class);
startActivityForResult(intent, 2);
Handle result on MainActivity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
String error=data.getStringExtra("MESSAGE");
//display error
}
}
Async
#Override
protected void onPostExecute(Void r) {
progressDialog.dismiss();
if(responseBody == "Api key does not found/match"){
Intent intent=new Intent();
intent.putExtra("Error",message);
setResult(2,intent);
finish();
}else {
byte[] imageAsBytes = Base64.decode(encode_string.getBytes(), Base64.DEFAULT);
//System.out.println(imageAsBytes);
Intent intent = new Intent(getActivity().getApplicationContext(), ViewActivity.class);
intent.putExtra("filePath", imageAsBytes);
//intent.putExtra("data", text);
startActivity(intent);
}
}

instantiateItem is calling 3 times and button is not clickable

instantiateItem is calling 3 times and buttons are not clickable
#Override
public Object instantiateItem(ViewGroup container, int position) {
// TODO Auto-generated method stub
inflater1 = (LayoutInflater) context1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View itemView = inflater1.inflate(R.layout.pagerlayout, container,
false);
Log.v("", "CHecking foregroung3");
((ScrollView)itemView. findViewById(R.id.scrollview)).scrollTo(0, 0);
articleTitle_textview = (TextView)itemView.findViewById(R.id.articletitle);
postingTime_textview = (TextView)itemView.findViewById(R.id.postingtime);
articleContent_webview = (WebView)itemView.findViewById(R.id.webview);
csSliderShow=(RelativeLayout)itemView.findViewById(R.id.slide);
countTxt = (TextView)itemView.findViewById(R.id.Count_textView);
previousTxt = (TextView)itemView.findViewById(R.id.prev_textview);
nextText = (TextView)itemView.findViewById(R.id.next_textview);
tab_layout_parent = (RelativeLayout)itemView.findViewById(R.id.tab_layout_parent);
tab_layout = (LinearLayout)itemView.findViewById(R.id.tab_layout);
relatedTxt=(TextView)itemView.findViewById(R.id.related);
relatedArticlesLinearLayoutGridView = (LinearLayout)itemView.findViewById(R.id.linear_related_articles_gridview);
gridView = new ExpandableHeightGridView(ArticleViewActivity.this);
articleContent_webview.invalidate();
//WebView wv = (WebView) findViewById(R.id.webview);
articleContent_webview.getSettings().setBuiltInZoomControls(false);
articleContent_webview.getSettings().setJavaScriptEnabled(true);
try{
/*if (indexofArticle >= 0)
{
if(relatedArticlesLinearLayoutGridView.getChildAt(0) != null)
{
int movement = relatedArticlesLinearLayoutGridView.getChildAt(0).getWidth()* indexofArticle;
//mHoriArticleViewList.scrollTo(movement, 0);
}
}*/
articleTitle_textview.setText(fetchmodel.mTitle);
postingTime_textview.setText(fetchmodel.mPubDate);
String s="<head><style><meta name='viewport' content='target-densityDpi=device-dpi' body{font-size:17px;}/></style></head>";
String addwidth = fetchmodel.mHtmlText;
//Log.v("","Checking Text Before:"+fetchmodel.mHtmlText);
String addwidth1 =addwidth.replace("w=320&q=", "w="+width+"&q=");
articleContent_webview.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
Log.v("URL : ", url);
if(url.contains("http:"))
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
return true;
}
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
}
#Override
public void onPageStarted(WebView view, String url,
Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
});
articleContent_webview.getSettings().setJavaScriptEnabled(true);
articleContent_webview.loadDataWithBaseURL("", s+addwidth1, "text/html", "utf8", "");
//Log.v("","Checking Text After:"+addwidth1);
if(fetchmodel.PhotoFeatureList.size() > 0)
{
csSliderShow.setVisibility(View.VISIBLE);
articleTitle_textview.setVisibility(View.VISIBLE);
postingTime_textview.setVisibility(View.VISIBLE);
csSliderShow.invalidate();
int valuimg=imagNum+1;
countTxt.setText("Slide "+valuimg+" of "+fetchmodel.PhotoFeatureList.size());
String image_url = fetchmodel.PhotoFeatureList.get(imagNum).imgUrl;
String image_url1 = image_url.replace("w=100", "w=300");
csImageLoader.DisplayImage(image_url1, R.drawable.loading, csImageSlider, 0);
titleTxt.setText(fetchmodel.PhotoFeatureList.get(imagNum).subTitle);
headlineTxt.setText(fetchmodel.PhotoFeatureList.get(imagNum).headline);
}
else
{
csSliderShow.setVisibility(View.GONE);
articleTitle_textview.setVisibility(View.GONE);
postingTime_textview.setVisibility(View.GONE);
}
try{
if (fetchmodel.sectionContainerList.size()>0 ) {
Log.v("","CHECKING TABS:");
tab_layout_parent.setVisibility(View.VISIBLE);
tab1 = (Button)itemView.findViewById(R.id.tab1);
tab2 = (Button)itemView.findViewById(R.id.tab2);
tab3 = (Button)itemView.findViewById(R.id.tab3);
imgPoster = (ImageView)itemView.findViewById(R.id.imgPoster0);
TextView profile =(TextView)itemView.findViewById(R.id.profile0);
TextView photos =(TextView)itemView.findViewById(R.id.photos0);
TextView videos =(TextView)itemView.findViewById(R.id.videos0);
countTab = 100;
imgLoader.DisplayImage(fetchmodel.sectionContainerList.get(0).minSectionImgURL, R.drawable.loading, imgPoster, 7);
if (fetchmodel.sectionContainerList.size() == 1) {
tab2.setVisibility(View.GONE);
tab3.setVisibility(View.GONE);
tab1.setText(fetchmodel.sectionContainerList.get(0).minSectionTitle);
imgPoster.setVisibility(View.VISIBLE);
profile.setVisibility(View.VISIBLE);
photos.setVisibility(View.VISIBLE);
videos.setVisibility(View.VISIBLE);
}else if (fetchmodel.sectionContainerList.size() == 2) {
tab3.setVisibility(View.GONE);
tab1.setText(fetchmodel.sectionContainerList.get(0).minSectionTitle);
tab2.setText(fetchmodel.sectionContainerList.get(1).minSectionTitle);
imgPoster.setVisibility(View.VISIBLE);
profile.setVisibility(View.VISIBLE);
photos.setVisibility(View.VISIBLE);
videos.setVisibility(View.VISIBLE);
}else if(fetchmodel.sectionContainerList.size() >= 3){
Log.v("","CHECKING TABS:3");
tab1.setText(fetchmodel.sectionContainerList.get(0).minSectionTitle);
tab2.setText(fetchmodel.sectionContainerList.get(1).minSectionTitle);
tab3.setText(fetchmodel.sectionContainerList.get(2).minSectionTitle);
imgPoster.setVisibility(View.VISIBLE);
profile.setVisibility(View.VISIBLE);
photos.setVisibility(View.VISIBLE);
videos.setVisibility(View.VISIBLE);
imgLoader.DisplayImage(fetchmodel.sectionContainerList.get(0).minSectionImgURL, R.drawable.loading, imgPoster, 7);
}
tab1.setTextColor(Color.RED);
tab2.setTextColor(Color.BLACK);
tab3.setTextColor(Color.BLACK);
tab2.setBackgroundColor(getResources().getColor(R.color.darkgreen));
tab3.setBackgroundColor(Color.GRAY);
tab1.setFocusable(false);
tab2.setFocusable(false);
tab3.setFocusable(false);
tab1.setBackgroundDrawable(null);
tab2.setBackgroundResource(R.drawable.back_button);
tab3.setBackgroundResource(R.drawable.back_button);
tab1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
tab1.setTextColor(Color.RED);
tab2.setTextColor(Color.BLACK);
tab3.setTextColor(Color.BLACK);
tab2.setBackgroundColor(getResources().getColor(R.color.darkgreen));
tab3.setBackgroundColor(Color.GRAY);
tab1.setBackgroundDrawable(null);
tab2.setBackgroundResource(R.drawable.back_button);
tab3.setBackgroundResource(R.drawable.back_button);
countTab = 100;
imgLoader.DisplayImage(fetchmodel.sectionContainerList.get(0).minSectionImgURL, R.drawable.loading, imgPoster, 7);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
});
tab2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
tab1.setTextColor(Color.BLACK);
tab2.setTextColor(Color.RED);
tab3.setTextColor(Color.BLACK);
tab1.setBackgroundColor(Color.GRAY);
tab3.setBackgroundColor(Color.GRAY);
tab2.setBackgroundDrawable(null);
tab1.setBackgroundResource(R.drawable.back_button);
tab3.setBackgroundResource(R.drawable.back_button);
countTab = 200;
imgLoader.DisplayImage(fetchmodel.sectionContainerList.get(1).minSectionImgURL, R.drawable.loading, imgPoster, 7);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
});
tab3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
tab1.setTextColor(Color.BLACK);
tab2.setTextColor(Color.BLACK);
tab3.setTextColor(Color.RED);
tab1.setBackgroundColor(Color.GRAY);
tab2.setBackgroundColor(Color.GRAY);
tab3.setBackgroundDrawable(null);
tab2.setBackgroundResource(R.drawable.back_button);
tab1.setBackgroundResource(R.drawable.back_button);
countTab = 300;
imgLoader.DisplayImage(fetchmodel.sectionContainerList.get(2).minSectionImgURL, R.drawable.loading, imgPoster, 7);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
});
imgPoster.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
if(countTab == 100){
if(fetchmodel.sectionContainerList.get(0).minType.contains("actor")){
Intent intent = new Intent(ArticleViewActivity.this, ActorProfileActivity.class);
intent.putExtra("personID", fetchmodel.sectionContainerList.get(0).minEntryId);
startActivity(intent);
}else if(fetchmodel.sectionContainerList.get(0).minType.contains("movie"))
{
Intent intent = new Intent(ArticleViewActivity.this, MovieProfileActivity.class);
intent.putExtra("movieID", fetchmodel.sectionContainerList.get(0).minEntryId);
startActivity(intent);
}
}else if (countTab == 200) {
if(fetchmodel.sectionContainerList.get(1).minType.contains("actor")){
Intent intent = new Intent(ArticleViewActivity.this, ActorProfileActivity.class);
intent.putExtra("personID", fetchmodel.sectionContainerList.get(1).minEntryId);
startActivity(intent);
}else if(fetchmodel.sectionContainerList.get(1).minType.contains("movie"))
{
Intent intent = new Intent(ArticleViewActivity.this, MovieProfileActivity.class);
intent.putExtra("movieID", fetchmodel.sectionContainerList.get(1).minEntryId);
startActivity(intent);
}
}else if (countTab == 300) {
if(fetchmodel.sectionContainerList.get(2).minType.contains("actor")){
Intent intent = new Intent(ArticleViewActivity.this, ActorProfileActivity.class);
intent.putExtra("personID", fetchmodel.sectionContainerList.get(2).minEntryId);
startActivity(intent);
}else if(fetchmodel.sectionContainerList.get(2).minType.contains("movie"))
{
Intent intent = new Intent(ArticleViewActivity.this, MovieProfileActivity.class);
intent.putExtra("movieID", fetchmodel.sectionContainerList.get(2).minEntryId);
startActivity(intent);
}
}
}catch(Exception e)
{
e.printStackTrace();
}
}
});
profile.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
if(countTab == 100){
if(fetchmodel.sectionContainerList.get(0).minType.contains("actor")){
Intent intent = new Intent(ArticleViewActivity.this, ActorProfileActivity.class);
intent.putExtra("personID", fetchmodel.sectionContainerList.get(0).minEntryId);
startActivity(intent);
}else if(fetchmodel.sectionContainerList.get(0).minType.contains("movie"))
{
Intent intent = new Intent(ArticleViewActivity.this, MovieProfileActivity.class);
intent.putExtra("movieID", fetchmodel.sectionContainerList.get(0).minEntryId);
startActivity(intent);
}
}else if (countTab == 200) {
if(fetchmodel.sectionContainerList.get(1).minType.contains("actor")){
Intent intent = new Intent(ArticleViewActivity.this, ActorProfileActivity.class);
intent.putExtra("personID", fetchmodel.sectionContainerList.get(1).minEntryId);
startActivity(intent);
}else if(fetchmodel.sectionContainerList.get(1).minType.contains("movie"))
{
Intent intent = new Intent(ArticleViewActivity.this, MovieProfileActivity.class);
intent.putExtra("movieID", fetchmodel.sectionContainerList.get(1).minEntryId);
startActivity(intent);
}
}
else if (countTab == 300) {
if(fetchmodel.sectionContainerList.get(2).minType.contains("actor")){
Intent intent = new Intent(ArticleViewActivity.this, ActorProfileActivity.class);
intent.putExtra("personID", fetchmodel.sectionContainerList.get(2).minEntryId);
startActivity(intent);
}else if(fetchmodel.sectionContainerList.get(2).minType.contains("movie"))
{
Intent intent = new Intent(ArticleViewActivity.this, MovieProfileActivity.class);
intent.putExtra("movieID", fetchmodel.sectionContainerList.get(2).minEntryId);
startActivity(intent);
}
}
}catch(Exception e)
{
e.printStackTrace();
}
}
});
photos.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
if(countTab == 100){
if(fetchmodel.sectionContainerList.get(0).minType.contains("actor")){
Intent intent = new Intent(ArticleViewActivity.this, PhotosLandingActitivity.class);
intent.putExtra("photosID", fetchmodel.sectionContainerList.get(0).minEntryId);
intent.putExtra("type", fetchmodel.sectionContainerList.get(0).minType);
intent.putExtra("actions", "FetchPhotos");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}else if(fetchmodel.sectionContainerList.get(0).minType.contains("movie"))
{
Intent intent = new Intent(ArticleViewActivity.this, PhotosLandingActitivity.class);
intent.putExtra("photosID", fetchmodel.sectionContainerList.get(0).minEntryId);
intent.putExtra("type", fetchmodel.sectionContainerList.get(0).minType);
intent.putExtra("actions", "FetchPhotos");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}else if (countTab == 200) {
if(fetchmodel.sectionContainerList.get(1).minType.contains("actor")){
Intent intent = new Intent(ArticleViewActivity.this, PhotosLandingActitivity.class);
intent.putExtra("photosID", fetchmodel.sectionContainerList.get(1).minEntryId);
intent.putExtra("type", fetchmodel.sectionContainerList.get(1).minType);
intent.putExtra("actions", "FetchPhotos");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}else if(fetchmodel.sectionContainerList.get(1).minType.contains("movie"))
{
Intent intent = new Intent(ArticleViewActivity.this, PhotosLandingActitivity.class);
intent.putExtra("photosID", fetchmodel.sectionContainerList.get(1).minEntryId);
intent.putExtra("type", fetchmodel.sectionContainerList.get(1).minType);
intent.putExtra("actions", "FetchPhotos");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
else if (countTab == 300) {
if(fetchmodel.sectionContainerList.get(2).minType.contains("actor")){
Intent intent = new Intent(ArticleViewActivity.this, PhotosLandingActitivity.class);
intent.putExtra("photosID", fetchmodel.sectionContainerList.get(2).minEntryId);
intent.putExtra("type", fetchmodel.sectionContainerList.get(2).minType);
intent.putExtra("actions", "FetchPhotos");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}else if(fetchmodel.sectionContainerList.get(2).minType.contains("movie"))
{
Intent intent = new Intent(ArticleViewActivity.this, PhotosLandingActitivity.class);
intent.putExtra("photosID", fetchmodel.sectionContainerList.get(2).minEntryId);
intent.putExtra("type", fetchmodel.sectionContainerList.get(2).minType);
intent.putExtra("actions", "FetchPhotos");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
}catch(Exception e)
{
e.printStackTrace();
}
}
});
videos.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
if(countTab == 100){
if(fetchmodel.sectionContainerList.get(0).minType.contains("actor")){
Intent intent = new Intent(ArticleViewActivity.this, LatestPhotosActivity.class);
intent.putExtra("videoID", fetchmodel.sectionContainerList.get(0).minEntryId);
intent.putExtra("whichscreen", 200);
intent.putExtra("type", "actor");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}else if(fetchmodel.sectionContainerList.get(0).minType.contains("movie"))
{
Intent intent = new Intent(ArticleViewActivity.this, LatestPhotosActivity.class);
intent.putExtra("videoID", fetchmodel.sectionContainerList.get(0).minEntryId);
intent.putExtra("whichscreen", 200);
intent.putExtra("type", "movie");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}else if (countTab == 200) {
if(fetchmodel.sectionContainerList.get(1).minType.contains("actor")){
Intent intent = new Intent(ArticleViewActivity.this, LatestPhotosActivity.class);
intent.putExtra("videoID", fetchmodel.sectionContainerList.get(1).minEntryId);
intent.putExtra("whichscreen", 200);
intent.putExtra("type", "actor");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}else if(fetchmodel.sectionContainerList.get(1).minType.contains("movie"))
{
Intent intent = new Intent(ArticleViewActivity.this, LatestPhotosActivity.class);
intent.putExtra("videoID", fetchmodel.sectionContainerList.get(1).minEntryId);
intent.putExtra("whichscreen", 200);
intent.putExtra("type", "movie");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}else if (countTab == 300) {
if(fetchmodel.sectionContainerList.get(2).minType.contains("actor")){
Intent intent = new Intent(ArticleViewActivity.this, LatestPhotosActivity.class);
intent.putExtra("videoID", fetchmodel.sectionContainerList.get(2).minEntryId);
intent.putExtra("whichscreen", 200);
intent.putExtra("type", "actor");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}else if(fetchmodel.sectionContainerList.get(2).minType.contains("movie"))
{
Intent intent = new Intent(ArticleViewActivity.this, LatestPhotosActivity.class);
intent.putExtra("videoID", fetchmodel.sectionContainerList.get(2).minEntryId);
intent.putExtra("whichscreen", 200);
intent.putExtra("type", "movie");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
}catch(Exception e)
{
e.printStackTrace();
}
}
});
}
}catch(Exception e)
{
e.printStackTrace();
}
if(relatedArticlesLinearLayoutGridView != null && relatedArticlesLinearLayoutGridView.getChildCount() > 0)
{
relatedArticlesLinearLayoutGridView.removeAllViews();
relatedArticlesLinearLayoutGridView = (LinearLayout)findViewById(R.id.linear_related_articles_gridview);
}
gridView.setNumColumns(2);
gridView.setAdapter(new LazyAdapterForRelatedArticles(mContext,fetchmodel.reLatedArticlesList));
gridView.setExpanded(true);
if(fetchmodel.reLatedArticlesList.size() > 0)
{
Log.v("","checking related:");
relatedTxt.setVisibility(View.VISIBLE);
relatedArticlesLinearLayoutGridView.setVisibility(View.VISIBLE);
}
else
{
relatedTxt.setVisibility(View.GONE);
relatedArticlesLinearLayoutGridView.setVisibility(View.GONE);
}
relatedArticlesLinearLayoutGridView.addView(gridView);
previousTxt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
try {
imagNum--;
if(imagNum < 0)
{
imagNum=fetchmodel.PhotoFeatureList.size()-1;
}
int valuimg=imagNum+1;
countTxt.setText("Slide "+valuimg+" of "+fetchmodel.PhotoFeatureList.size());
String image_url = fetchmodel.PhotoFeatureList.get(imagNum).imgUrl;
String image_url1 = image_url.replace("w=100", "w=300");
csImageLoader.DisplayImage(image_url1, R.drawable.loading, csImageSlider, 0);
titleTxt.setText(fetchmodel.PhotoFeatureList.get(imagNum).subTitle);
headlineTxt.setText(fetchmodel.PhotoFeatureList.get(imagNum).headline);
getTracker().trackPageView("ArticleViewPage- Image:"+fetchmodel.PhotoFeatureList.get(imagNum).imgUrl);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
});
nextText.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{try {
imagNum++;
if(imagNum > fetchmodel.PhotoFeatureList.size()-1)
{
imagNum=0;
}
int valuimg=imagNum+1;
countTxt.setText("Slide "+valuimg+" of "+fetchmodel.PhotoFeatureList.size());
String image_url = fetchmodel.PhotoFeatureList.get(imagNum).imgUrl;
String image_url1 = image_url.replace("w=100", "w=300");
csImageLoader.DisplayImage(image_url1, R.drawable.loading, csImageSlider, 0);
titleTxt.setText(fetchmodel.PhotoFeatureList.get(imagNum).subTitle);
headlineTxt.setText(fetchmodel.PhotoFeatureList.get(imagNum).headline);
getTracker().trackPageView("ArticleViewPage- Image:"+fetchmodel.PhotoFeatureList.get(imagNum).imgUrl);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
});
gridView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
pageLoadNum = 5050;
strEntryId=csFetchArticle.reLatedArticlesList.get(position).minEntryID;
imagNum=0;
if(csFetchArticle.PhotoFeatureList != null && csFetchArticle.PhotoFeatureList.size() > 0)
{
csFetchArticle.PhotoFeatureList.clear();
}
if(csFetchArticle.reLatedArticlesList != null && csFetchArticle.reLatedArticlesList.size() > 0)
{
csFetchArticle.reLatedArticlesList.clear();
}
articleContent_webview = (WebView)findViewById(R.id.webview);
sendEmptyMessageSync(SHOW_PROGRESS_DIALOG);
sendEmptyMessageAsync(FETCH_ARTICLE);
}
});
}catch(Exception e){
e.printStackTrace();
}
((ViewPager) container).addView(itemView);
//csViePageAdapter.notifyDataSetChanged();
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((RelativeLayout) object);
}
}

Android share intent for facebook- share text AND link

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
}
}
}

Categories

Resources