I'm developing an app that, in the first activity, it takes a photo saved, and it is shown in an imageview, but at the same time I want a gridview to be created in another activity, which will recover each captured image, showing in order.
So far I can take a picture, save it in the gallery, and show it on the imageview, but when I go to the other activity, it shows the gridview retrieving all the photos from the gallery, could someone help me? This is my schedule:
Activity in which you take the photo and save it:
public class Main2Activity extends AppCompatActivity {
private Uri uri;
private static final int CAMERA = 1;
private String caminhoDaImagem;
ImageView imageViewFoto;
private EditText etCliente;
private EditText etPostes;
private EditText etObservacao;
String mCurrentPhotoPath;
String imgSaved;
private Button botao;
#Override
public void onBackPressed() { //Botão BACK padrão do android
startActivity(new Intent(this, MainActivity.class)); //O efeito ao ser pressionado do botão (no caso abre a activity)
//finishAffinity(); //Método para matar a activity e não deixa-lá indexada na pilhagem
return;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
final Button btnSalvarRelatorio = (Button) findViewById(R.id.btnAvancar);
Button btnAvancar = (Button) findViewById(R.id.btnAvancar);
//CÓDIGO NECESSÁRIO PARA A PERMISSÃO A MEMÓRIA INTERNA
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000);
}
//PERMISSÃO DE ACESSO Á CAEMRA
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 0);
}
findViewById(R.id.btnTirarFotos).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tirarFoto();
}
});
findViewById(R.id.btnAvancar).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chamar3Activity();
}
});
}
/*public void onRequestPermissionResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResult) {
switch (requestCode) {
case 1000:
if (grantResult[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permissão Concedida!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Permissão não Concedida!", Toast.LENGTH_SHORT).show();
finish();
}
}
}*/
private void chamar3Activity() {
Intent novaintent = new Intent();
novaintent.setClass(Main2Activity.this, Main3Activity.class);
startActivity(novaintent);
finish();
}
//DANDO A FUNÇÃO AO BOTÃO DE TIRAR FOTO
public void tirarFoto() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
}
//SALVANDO IMAGEM DA CAMERA E DIRECIONANDO ELA A UM IMAGEVIEW
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
File file = null;
try {
file = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
}
Bitmap image = (Bitmap) data.getExtras().get("data");
ImageView imageview = (ImageView) findViewById(R.id.imageView2);
imageview.setImageBitmap(image);
// Chame este método pra obter a URI da imagem
Uri uri = getImageUri(getApplicationContext(), image);
// Em seguida chame este método para obter o caminho do arquivo
File file = new File(getRealPathFromURI(uri));
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "CANCELADO", Toast.LENGTH_LONG).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmm").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
Toast.makeText(this, mCurrentPhotoPath, Toast.LENGTH_LONG).show();
return image;
}
** Activity where the Grid View will be shown: **
public class MainActivity extends AppCompatActivity {
GridView gv;
ArrayList<File> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = imageRead(Environment.getExternalStorageDirectory());
gv = (GridView) findViewById(R.id.gv);
gv.setAdapter(new GridAdapter());
}
class GridAdapter extends BaseAdapter{
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.single_grid, parent, false);
ImageView imageView = convertView.findViewById(R.id.imageView);
imageView.setImageURI(Uri.parse( getItem(position) . toString()));
return convertView;
}
}
ArrayList<File> imageRead(File root){
ArrayList<File> a = new ArrayList<>();
File[] files = root.listFiles();
for(int i =0; i< files.length; i++){
if(files[i].isDirectory()){
a.addAll(imageRead(files[i]));
}
else{
if( files[i].getName().endsWith(".jpg")){
a.add(files[i]);
}
}
}
return a;
}
Related
I was developing an App where I have the intention to keep data into a RoomDatabase.
I get the erro on the title when I try to sart my App.
I don't know if it for using a kotlin class in combination with other java class.
My kotlin file is the Converters.class with I use to keep Image into the database.
Converters.kotlin
class Converters_kotlin {
#TypeConverter
fun fromBitmap(bitmap:Bitmap): ByteArray{
val outputStream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
return outputStream.toByteArray()
}
#TypeConverter
fun toBitmap(byteArray: ByteArray):Bitmap{
return BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size)
}
}
Birddb.java
#Database(
entities = {BirdRoom.class},
version = 1
)
#TypeConverters({Converters_kotlin.class})
public abstract class Birddb extends RoomDatabase {
private static volatile Birddb INSTANCE;
private static final int NUMBER_OF_THREADS = 1;
static final ExecutorService databaseWriteExecutor = Executors.newFixedThreadPool(NUMBER_OF_THREADS);
public abstract BirdDAO birdDAO();
public static Birddb getDatabase(final Context context) {
if (INSTANCE == null) {
synchronized (Birddb.class) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
Birddb.class, "user_database")
.build();
}
}
}
return INSTANCE;
}
}
And the fragment where I call the database:
CaptureFragment.java
public class CaptureFragment extends Fragment {
private CaptureViewModel mViewModel;
private ImageButton btnCamara;
private ImageView mPhotoImageView;
public static final int REQUEST_CODE_TAKE_PHOTO = 0 /*1*/;
private String mCurrentPhotoPath;
private Uri photoURI;
private EditText Ettitulo;
public static CaptureFragment newInstance() {
return new CaptureFragment();
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
Ettitulo = (EditText) container.findViewById(R.id.EtInstantanea);
mPhotoImageView = (ImageView) container.findViewById(R.id.imgCapture);
mPhotoImageView.setImageDrawable(null);
btnCamara = (ImageButton) container.findViewById(R.id.btnCapture);
btnCamara.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//1.Open the camera.
if (v == mPhotoImageView) {
if (ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) getContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
} else {
ActivityCompat.requestPermissions((Activity) getContext(),
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
225);
}
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) getContext(),
Manifest.permission.CAMERA)) {
} else {
ActivityCompat.requestPermissions((Activity) getContext(),
new String[]{Manifest.permission.CAMERA},
226);
}
} else {
dispatchTakePictureIntent();
}
}
//2. Recover the photo and write into internal storage.
//TODO: Use AlerrtDiolog para solicitar nombre de la foto.
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
//Send the Jornal, and keep into DB.
String titulo = Ettitulo.getText().toString();
Bundle bundle = new Bundle();
bundle.putString("edtValue", titulo);
bundle.putString("image", mCurrentPhotoPath);
//Swicth the () -> fragment
FragmentManager manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
JournalFragment jf = new JournalFragment();
jf.setArguments(bundle);
transaction.replace(container.getId(),jf);
transaction.commit();
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
Toast.makeText(getContext(), "Foto NO añadida a su diario personal.", Toast.LENGTH_LONG).show();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
Intent intento1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File foto = new File(getActivity().getExternalFilesDir(null), mCurrentPhotoPath);
intento1.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(foto));
startActivity(intento1);
//3. Set the photo into the ImageView,
Bitmap bitmap1 = BitmapFactory.decodeFile(getActivity().getExternalFilesDir(null)+"/"+Ettitulo.getText().toString());
Drawable d = new BitmapDrawable(getResources(), bitmap1);
mPhotoImageView.setImageDrawable(d);
//4. Ask if the user want to keep that pjoto into his jornal.
AlertDialog.Builder builder1 = new AlertDialog.Builder(getContext());
builder1.setMessage("¿Le gustaría guardar esta foto en su diario?");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//Instancio la BBDD local..
Birddb db = Room.databaseBuilder(getContext(),
Birddb.class, "database-name").build();
//Añado el objeto Bird a la BBDD local.
BirdDAO birdDAO = db.birdDAO();
//List<Bird> users = userDao.getAll();
AsyncTask.execute(new Runnable() {
#Override
public void run() {
//Guardar Objeto Bird en la BBDD.
String descripcion = Ettitulo.getText().toString();
BirdRoom bird = new BirdRoom(descripcion, mCurrentPhotoPath);
Birddb.getDatabase(getContext()).birdDAO().insertBird(bird);
Toast.makeText(getContext(), "Ejemplar añadido correctamente a su diario", Toast.LENGTH_LONG).show();
}
});
}
});
builder1.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(getContext(), "No se ha añadido la foto actual a su diario", Toast.LENGTH_LONG).show();
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
});
return inflater.inflate(R.layout.fragment_capture, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mViewModel = new ViewModelProvider(this).get(CaptureViewModel.class);
}
private void checkExternalStoragePermission() {
if (ContextCompat.checkSelfPermission((Activity)getContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
Log.e(TAG, "Permission not granted WRITE_EXTERNAL_STORAGE.");
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) getContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
} else {
ActivityCompat.requestPermissions((Activity) getContext(),
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
225);
}
}if (ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
Log.e(TAG, "Permission not granted CAMERA.");
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) getContext(),
Manifest.permission.CAMERA)) {
} else {
ActivityCompat.requestPermissions((Activity) getContext(),
new String[]{Manifest.permission.CAMERA},
226);
}
}
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "MyPicture");
values.put(MediaStore.Images.Media.DESCRIPTION, "Photo taken on " + System.currentTimeMillis());
photoURI = getActivity().getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//Uri photoURI = FileProvider.getUriForFile(AddActivity.this, "com.example.android.fileprovider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_CODE_TAKE_PHOTO);
}
}
}
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 = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_TAKE_PHOTO && resultCode == RESULT_OK) {
Bitmap bitmap;
try {
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), photoURI);
mPhotoImageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Ìf you guess how to solve it, take thanks for advance!
[EDIT]
Add a capture of the error return by Android Studio.
This is the code I am working on, make a multiple selection of images and the most in a gridview array that calls it ImageList, but I would recommend converting the images to a base64 to have more efficiency when uploading and displaying the images, so I looked for examples and documentation and I found a way to convert them, but I was somewhat confused, because the array where the images are stored was ready List of images I had to pass it to a chain of chains, but I did not understand very well how to upload them to the firebase both the storage and the database, since they are images that will be saved of products that will be shown in the store this is the code
here is the activity where the data will be uploaded, the data as name price and description already uploaded to the database the imagenes not.
public class adminActivity extends AppCompatActivity {
private EditText nombreP, precioP, infoP;
int PICK_IMAGE = 100;
Uri imagenUri;
Button btnCargar;
Button btnEditar;
GridView gvImagenes;
List<Uri> listaImagenes = new ArrayList<>();
List<Uri> listaBase64Imagenes = new ArrayList<>();
GridViewAdapter baseAdapter;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
StorageReference mStorageRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
/*INICIALIZAMOS LA CONEXION CON FIREBASE*/
FirebaseApp.initializeApp(this);
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference();
mStorageRef = FirebaseStorage.getInstance().getReference();
nombreP = (EditText) findViewById(R.id.nameProducto);
precioP = (EditText) findViewById(R.id.precioProducto);
infoP = (EditText) findViewById(R.id.infoProducto);
gvImagenes = findViewById(R.id.gvImagenes);
btnEditar = findViewById(R.id.editar);
btnCargar = (Button) findViewById(R.id.cargar);
btnEditar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
abrirGaleria();
}
});
btnCargar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String nombre = nombreP.getText().toString();
String precio = precioP.getText().toString().trim();
String infor = infoP.getText().toString();
if (!nombre.isEmpty() && !precio.isEmpty() && !infor.isEmpty()){
cargarUsuario();
limpiarCaja();
}else {
Toast.makeText(adminActivity.this,"Deben llenarse todos los campos.",Toast.LENGTH_SHORT).show();
return;
}
}
});
}
private void limpiarCaja() {
nombreP.setText("");
precioP.setText("");
infoP.setText("");
}
public void cargarUsuario() {
listaBase64Imagenes.clear();
for (int i = 0 ; i < listaImagenes.size() ; i++){
try {
InputStream is = getContentResolver().openInputStream(listaImagenes.get(i));
Bitmap bitmap = BitmapFactory.decodeStream(is);
String cadena = convertirUriToBase64(bitmap);
enviarImagen(cadena);
bitmap.recycle();
} catch (IOException e){
}
}
//Toast.makeText(this, "Producto Registrado", Toast.LENGTH_LONG).show();
String nombre = nombreP.getText().toString();
String precio = precioP.getText().toString();
String infor = infoP.getText().toString();
productos p = new productos();
p.setUid(UUID.randomUUID().toString());
p.setNombre(nombre);
p.setPrecio(precio);
p.setInformacion(infor);
databaseReference.child("Productos").child(p.getUid()).setValue(p);
Toast.makeText(adminActivity.this,"Agregado.",Toast.LENGTH_SHORT).show();
}
private void enviarImagen(final String cadena) {
StorageReference folderRef = mStorageRef.child("imagenesProductos");
folderRef.putFile((Uri) listaImagenes).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful());
Uri downloadUri = uriTask.getResult();
}
});
}
private String convertirUriToBase64(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] bytes = baos.toByteArray();
String encode = Base64.encodeToString(bytes, Base64.DEFAULT);
return encode;
}
private void abrirGaleria() {
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE,true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "SELECCIONA LAS IMAGENES"),PICK_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ClipData clipData = data.getClipData();
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE){
/*PARA UNA SOLA IMAGEN*/
if (clipData == null){
imagenUri = data.getData();
listaImagenes.add(imagenUri);
}
}else {
/*PARA VARIAS IMAGENES*/
for (int i = 0; i < clipData.getItemCount(); i++){
listaImagenes.add(clipData.getItemAt(i).getUri());
}
}
baseAdapter = new GridViewAdapter(adminActivity.this, listaImagenes);
gvImagenes.setAdapter(baseAdapter);
}
}
and here is the gridview adapter code
#Override
public int getCount() {
return listaImagenes.size();
}
#Override
public Object getItem(int position) {
return listaImagenes.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
if (view == null){
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.item_carga_imagenes, null);
}
ImageView ivImagen = view.findViewById(R.id.ivImagen);
ImageButton ibtnEliminar = view.findViewById(R.id.ibtnEliminar);
ivImagen.setImageURI(listaImagenes.get(position));
ibtnEliminar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listaImagenes.remove(position);
notifyDataSetChanged();
}
});
return view;
}
}
here i point out the method where i try to make the connection to the storage of firebase, they could help to rebuild it in order to be able to upload them to the storage and also to the database with their respective name, price and description
private void enviarImagen(final String cadena) {
StorageReference folderRef = mStorageRef.child("imagenesProductos");
folderRef.putFile((Uri) listaImagenes).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful());
Uri downloadUri = uriTask.getResult();
}
});
}
Your question is still little bit of confusion, In my case what i understand from you, you want to store images to firebase in BASE64 format.
String encode = Base64.encodeToString(bytes, Base64.DEFAULT);
Now, you don't have you store string, you can simply store byte[] in firbase and retrive it and just converted it to bitmap, here is a example for you:
byte[] byteImage = Base64.decode(encode, Base64.DEFAULT);
Bitmap imageBitmap = BitmapFactory.decodeByteArray(byteImage, 0, decodedString.length);
I want to write a module where on a click of a button, the camera opens and I can click and capture an image. If I don't like the image, I can delete it and click one more image, and then select the image and it should return back and display that image in the activity.
The problem comes when I took a picture the camera application gets crashed and when I took a picture from the gallery the pic doesn't show in image view.
This is the script I wrote:
public class MainpageActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
final int TAKE_PICTURE = 1;
final int ACTIVITY_SELECT_IMAGE = 2;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainpage);
Toolbar toolbar = findViewById(R.id.toolbar);
imageView = (ImageView)this.findViewById(R.id.imageView1);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setImageResource(R.drawable.ic_camera_alt_black_24dp);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{ RxPermissions rxPermissions = new RxPermissions(MainpageActivity.this);
rxPermissions
.request(Manifest.permission.CAMERA) // ask single or multiple permission once
.subscribe(granted -> {
if (granted) {
selectImage();
} else {
Toast.makeText(MainpageActivity.this, "Permission of camera is denied", Toast.LENGTH_SHORT).show();
}
});
}
});
private File savebitmap(Bitmap bmp) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
// String temp = null;
File file = new File(extStorageDirectory, "temp.png");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, "temp.png");
}
try {
outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return file;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainpageActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options,new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if(options[which].equals("Take Photo"))
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, TAKE_PICTURE);
}
else if(options[which].equals("Choose from Gallery"))
{
Intent intent=new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, ACTIVITY_SELECT_IMAGE);
}
else if(options[which].equals("Cancel"))
{
dialog.dismiss();
}
}
});
builder.show();
}
public void onActivityResult(int requestcode,int resultcode,Intent intent)
{
super.onActivityResult(requestcode, resultcode, intent);
if(resultcode==RESULT_OK)
{
if(requestcode==TAKE_PICTURE)
{
Bitmap photo = (Bitmap)intent.getExtras().get("data");
Drawable drawable=new BitmapDrawable(photo);
imageView.setBackgroundDrawable(drawable);
}
else if(requestcode==ACTIVITY_SELECT_IMAGE)
{
Uri selectedImage = intent.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Drawable drawable=new BitmapDrawable(thumbnail);
imageView.setBackgroundDrawable(drawable);
}
}
}
}
#Uma : Please follow this steps and change your code.
Step 1 - add both two line in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And also add this properties in application tag in manifest file:
android:largeHeap="true"
android:hardwareAccelerated="false"
Step - 2 - import lib in build.gradle file
implementation 'com.karumi:dexter:4.2.0' // for handling runtime permissions
Step - 3 - In your MainpageActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
this.fab = (FloatingActionButton) this.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
CheckPermission();
}
});
}
private void CheckPermission(){
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
// check if all permissions are granted
if (report.areAllPermissionsGranted()) {
selectImage();
}
// check for permanent denial of any permission
if (report.isAnyPermissionPermanentlyDenied()) {
// permission is denied permenantly, navigate user to app settings
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
})
.onSameThread()
.check();
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(MainActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
private File savebitmap(Bitmap bmp) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
// String temp = null;
File file = new File(extStorageDirectory, "temp.png");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, "temp.png");
}
try {
outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return file;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.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"))
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#SuppressLint("LongLogTag")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}}
Hope it helps you.
I think you should try to add this "android:required="true".
<uses-feature android:name="android.hardware.camera"
android:required="true" />
First of all, you need to handle with permissions
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
After this, you can use this for opening gallery with button
//opening image chooser option
choose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
}
});
And with this function, you can show the image on UI
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//getting image from gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting image to ImageView
image.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Also, you can convert image to bitmap64:
//converting image to base64 string
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
byte[] imageBytes = baos.toByteArray();
final String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);
I am making an app in which a feature that user can upload images and video to server
it was working well on activity but now I want to use it in a fragment. I try to code effectively, efficiently and I am not getting any error during compiling and my app runs successfully but when I click on fragment it shows "unfortunately app has stopped " and in log cat I am getting this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Parcelable android.os.Bundle.getParcelable(java.lang.String)' on a null object reference
and its points this line:
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this line ➦ fileUri = savedInstanceState.getParcelable("file_uri");
}
i don't know whats wrong
my code:
public class TabFragment4 extends Fragment implements View.OnClickListener{
View parentHolder;
private static final String TAG = MainActivity.class.getSimpleName();
int req_code = 100;
int video_code = 20;
String path;
Uri selectedImageUri;
// Camera activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 10;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
Context mContext;
private Uri fileUri; // file url to store image/video
private ImageButton btnCapturePicture, btnRecordVideo,gallerybtn , videobtn,b1,location;
public TabFragment4() {
// Required empty public constructor
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
parentHolder = inflater.inflate(R.layout.fragment_tab_fragment4, container, false);
final LocationManager manager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(getActivity());
// Setting Dialog Title
mAlertDialog.setTitle("Location not available, Open GPS?")
.setMessage("Activate GPS to use Location Service ?")
.setPositiveButton("Open Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
})
.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).show();
// Call your Alert message
}
btnCapturePicture = (ImageButton)parentHolder.findViewById(R.id.btnCapturePicture);
btnRecordVideo = (ImageButton)parentHolder. findViewById(R.id.btnRecordVideo);
gallerybtn=(ImageButton)parentHolder.findViewById(R.id.imagegallery);
videobtn = (ImageButton)parentHolder.findViewById(R.id.videogallery);
location=(ImageButton)parentHolder.findViewById(R.id.location);
videobtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
video();
}
});
gallerybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
galleryimage();
}
});
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
captureImage();
}
});
/**
* Capture image button click event
*/
btnRecordVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
recordVideo();
}
});
/**
* Record video button click event
*/
btnRecordVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
recordVideo();
}
});
return parentHolder;
}
public void video(){
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select file to upload "), video_code);
}
public void galleryimage(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select file to upload "), req_code);
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Launching camera app to record video
*/
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
fileUri = savedInstanceState.getParcelable("file_uri");
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == req_code) {
selectedImageUri = data.getData();
if (resultCode ==Activity. RESULT_OK) {
path = getPath(selectedImageUri);
launchUpload(true);
System.out.println("selectedPath1 : " + path);
}
}
if (requestCode == video_code) {
selectedImageUri = data.getData();
if (resultCode == Activity. RESULT_OK) {
path = getPath(selectedImageUri);
launchUpload(false);
System.out.println("selectedPath1 : " + path);
}
}
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
//successfully captured the image
// launching upload activity
launchUploadActivity(true);
//Intent intent = new Intent(this,UploadActivity.class);
//startActivity(intent);
} else if (resultCode ==Activity. RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getActivity(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getActivity(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
// video successfully recorded
// launching upload activity
launchUploadActivity(false);
} else if (resultCode == Activity.RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getActivity(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getActivity(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
private void launchUploadActivity(boolean isImage) {
Intent i = new Intent(getActivity(), UploadActivity.class);
i.putExtra("filePath", fileUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);
}
private void launchUpload(boolean isImage) {
Intent i = new Intent(getActivity(), UploadActivity.class);
i.putExtra("filePath", path);
i.putExtra("isImage", isImage);
startActivity(i);
}
/**
* ------------ Helper Methods ----------------------
* */
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
Config.IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "
+ Config.IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
#Override
public void onClick(View v) {
}
}
Uri imageUri = data.getData();
Bitmap bitmap= null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), imageUri);
} catch (IOException e) {
e.printStackTrace();
}
Seems savedInstanceState == null so use something like this:
if (savedInstanceState != null) {
fileUri = savedInstanceState.getParcelable("file_uri");
} else {
fileUri = ??? - what You want do to in else case;
}
This is my code i capture image and share successfully but can't upload video
public class CaptureActivity extends AppCompatActivity {
ShareButton shareButton;
private ImageView imgPreview;
private VideoView videoPreview;
private Button btnCapture;
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private Uri fileUri;
private static final String IMAGE_DIRECTORY_NAME = "CityApp";
static File mediaFile;
static File mediaStorageDir;
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_capture);
imgPreview = (ImageView) findViewById(R.id.imageView);
videoPreview = (VideoView) findViewById(R.id.videoPreview);
btnCapture = (Button) findViewById(R.id.btn_Capture);
shareButton = (ShareButton) findViewById(R.id.fb_share_button);
// shareButton.setFragment(this);
shareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
publishImage();
// publishVideo();
}
});
btnCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
private void selectImage() {
final CharSequence[] options = {"Take Photo", "Tack Video", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(CaptureActivity.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")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
} else if (options[item].equals("Tack Video")) {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on scren orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
/**
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// hide video preview
videoPreview.setVisibility(View.GONE);
imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options);
imgPreview.setImageBitmap(bitmap);
}
catch (NullPointerException e) {
e.printStackTrace();
}
}
/**
* Previewing recorded video
*/
private void previewVideo() {
try {
// hide image preview
imgPreview.setVisibility(View.GONE);
videoPreview.setVisibility(View.VISIBLE);
videoPreview.setVideoPath(fileUri.getPath());
// start playing
videoPreview.start();
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
public static File getOutputMediaFile(int type) {
// External sdcard location
mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
// preview the recorded video
previewVideo();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public void publishImage() {
// statusUpdates= new ContactsContract.StatusUpdates(getActivity().getApplicationContext());
// Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
BitmapFactory.Options options = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options);
SharePhoto photo = new SharePhoto.Builder()
.setBitmap(bitmap)
.setCaption("Testing with android")
.build();
SharePhotoContent content = new SharePhotoContent.Builder()
.addPhoto(photo)
.build();
shareButton.setShareContent(content);
}
public void publishVideo() {
Uri videoFileUri = fileUri;
ShareVideo shareVideo = new ShareVideo.Builder()
.setLocalUrl(videoFileUri)
.build();
ShareVideoContent content = new ShareVideoContent.Builder()
.setVideo(shareVideo)
.build();
shareButton.setShareContent(content);
}
}
i want use compile 'com.facebook.android:facebook-android-sdk:4.1.0' this library thanks in advance