I'm trying to add a set wallpaper button to my app that will set the wallpaper when I pull my image from firebase database. This is what I have so far. I've set the button up to automatically show up on every wallpaper snap shot. I've set a wallpaper in the past when the picture was stored on the phone but cant seem to figure out how to set it when pulling an image from firebase.
public class WallpapersAdapter extends RecyclerView.Adapter<WallpapersAdapter.WallpaperViewHolder> {
private Context mCtx;
private List<Wallpaper> wallpaperList;
public WallpapersAdapter(Context mCtx, List<Wallpaper> wallpaperList) {
this.mCtx = mCtx;
this.wallpaperList = wallpaperList;
}
#NonNull
#Override
public WallpaperViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mCtx).inflate(R.layout.recyclerview_wallpapers, parent, false);
return new WallpaperViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull WallpaperViewHolder holder, int position) {
Wallpaper w = wallpaperList.get(position);
holder.textView.setText(w.title);
Glide.with(mCtx)
.load(w.url)
.into(holder.imageView);
if(w.isFavorite){
holder.checkBoxFav.setChecked(true);
}
}
#Override
public int getItemCount() {
return wallpaperList.size();
}
class WallpaperViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, CompoundButton.OnCheckedChangeListener{
TextView textView;
ImageView imageView;
CheckBox checkBoxFav;
ImageButton buttonShare, buttonDownload;
Button setWallpaper;
public WallpaperViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_view_title);
imageView = itemView.findViewById(R.id.image_view);
checkBoxFav = itemView.findViewById(R.id.checkbox_favorite);
buttonShare = itemView.findViewById(R.id.button_share);
buttonDownload = itemView.findViewById(R.id.button_download);
setWallpaper = itemView.findViewById(R.id.set_wallpaper);
setWallpaper.setOnClickListener(this);
checkBoxFav.setOnCheckedChangeListener(this);
/*buttonShare.setOnClickListener(this);*/
/*buttonDownload.setOnClickListener(this);*/
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button_share:
shareWallpaper(wallpaperList.get(getAdapterPosition()));
break;
case R.id.button_download:
downloadWallpaper(wallpaperList.get(getAdapterPosition()));
break;
case R.id.set_wallpaper:
setWallpaper(wallpaperList.get(getAdapterPosition()));
break;
}
}
private void shareWallpaper(Wallpaper w){
((Activity) mCtx).findViewById(R.id.progressbar).setVisibility(View.VISIBLE);
Glide.with(mCtx)
.asBitmap()
.load(w.url)
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
((Activity) mCtx).findViewById(R.id.progressbar).setVisibility(View.GONE);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, getLocalBitmapUri(resource));
mCtx.startActivity(Intent.createChooser(intent, "The Wallpaper App"));
}
});
}
private Uri getLocalBitmapUri(Bitmap bmp){
Uri bmpUri = null;
try {
File file = new File(mCtx.getExternalFilesDir(Environment.DIRECTORY_PICTURES),
"the_wallpaper_app_" + System.currentTimeMillis() + ".png");
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
private void downloadWallpaper(final Wallpaper wallpaper){
((Activity) mCtx).findViewById(R.id.progressbar).setVisibility(View.VISIBLE);
Glide.with(mCtx)
.asBitmap()
.load(wallpaper.url)
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
((Activity) mCtx).findViewById(R.id.progressbar).setVisibility(View.GONE);
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = saveWallpaperAndGetUri(resource, wallpaper.id);
if(uri != null){
intent.setDataAndType(uri, "image/*");
mCtx.startActivity(Intent.createChooser(intent, "The Wallpaper App"));
}
}
});
}
private Uri saveWallpaperAndGetUri(Bitmap bitmap, String id){
if(ContextCompat.checkSelfPermission(mCtx, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
if(ActivityCompat.shouldShowRequestPermissionRationale((Activity) mCtx, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", mCtx.getPackageName(), null);
intent.setData(uri);
mCtx.startActivity(intent);
}else{
ActivityCompat.requestPermissions((Activity) mCtx, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100 );
}
return null;
}
File folder = new File(Environment.getExternalStorageDirectory().toString() + "/the_wallpaper_app" );
folder.mkdirs();
File file = new File(folder, id + ".jpg" );
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
return Uri.fromFile(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(FirebaseAuth.getInstance().getCurrentUser() == null){
Toast.makeText(mCtx, "Please login first", Toast.LENGTH_LONG).show();
compoundButton.setChecked(false);
return;
}
int position = getAdapterPosition();
Wallpaper w = wallpaperList.get(position);
DatabaseReference dbFavs = FirebaseDatabase.getInstance().getReference("users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child("favorites")
.child(w.category);
if(b){
dbFavs.child(w.id).setValue(w);
}else{
dbFavs.child(w.id).setValue(null);
}
}
}
private void setWallpaper(Wallpaper set) {
};
}
}
You can not directly set the image from database as wallpaper on your android device, for that first you have to download the image to your device and then you can set it as the background wallpaper.
You can use createTempFile(String prefix, String suffix) which creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.
Read more about this here.
If you'd rather want to store the file in your app directory, you can use a code like this:
File dir = new File(Environment.getExternalStorageDirectory(), "dir_name");
// Create dir if not exists
if(!dir.exists()) dir.mkdirs();
File mFile = new File(dir, "file_name");
Also to get bitmap from the file and use it to set as wallpaper, you may use a code similar to this:
Bitmap bitmap = BitmapFactory.decodeFile(mFile.getAbsolutePath());
//after converting it to bitmapDrawable you can set it as background using this
getWindow().setBackgroundDrawable
You may also use WallpaperManager for this like:
WallpaperManager.getInstance(getApplicationContext()).setBitmap(resource);
Related
I have a tabLayout with ImageView and when I Pick A image from the gallery and display it to Imageview then when I close the app the selected image is gone then I need to pick an image again.
And I know this one looks the same as my question but still not working
saving image picked from gallery for future use
I tried this code but the image still disappeared
https://github.com/martinsing/Image-Save-And-Retrieve-App
I also Read this other question but no one works
Image in ImageView disappear
public class FirstFragment extends Fragment implements View.OnClickListener{
ImageView imageButton1;
ImageButton imageButton2;
private Uri mImageUri;
private File mSnapFile;
private static final String ARG_URI_IMAGE_1 = "image1Uri";
private static final String ARG_URI_IMAGE_2 = "image2Uri";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.fragment_first, container, false);
imageButton1 = (ImageView) v.findViewById(R.id.firstimagebtn);
imageButton2 = (ImageButton)v.findViewById(R.id.secondimagebtn);
imageButton1.setOnClickListener(this::onClick);
imageButton2.setOnClickListener(this::onClick);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
String mImageUri = preferences.getString("image", null);
if (mImageUri != null) {
imageButton2.setImageURI(Uri.parse(mImageUri));
} else {
imageButton2.setImageResource(R.mipmap.ic_launcher);
}
return v;
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.firstimagebtn:
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent,0);
break;
case R.id.secondimagebtn:
Intent intent2 = new Intent(Intent.ACTION_PICK);
intent2.setType("image/*");
startActivityForResult(intent2,1);
break;
}
}
private void handleImageSelect(#Nullable Intent intent) {
if (saveContentLocally(intent)) {
try {
Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(mSnapFile));
imageButton1.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
throw new IllegalStateException("Saved the image file, but it doesn't exist!");
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case 0:
if(resultCode == Activity.RESULT_OK){
handleImageSelect(data);
}
break;
case 1:
if(resultCode == Activity.RESULT_OK){
mImageUri = data.getData();
// Saves image URI as string to Default Shared Preferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("image", String.valueOf(mImageUri));
editor.commit();
// Sets the ImageView with the Image URI
imageButton2.setImageURI(mImageUri);
imageButton2.invalidate();
}
break;
}
}
/**
* Saves the file from the ACTION_PICK Intent locally to {#link #mSnapFile} to be accessed by our FileProvider
*/
private boolean saveContentLocally(#Nullable Intent intent) {
if (intent == null || intent.getData() == null) {
return false;
}
InputStream inputStream;
try {
inputStream = getActivity().getContentResolver().openInputStream(intent.getData());
} catch (FileNotFoundException e) {
Toast.makeText(getActivity(), "Could not open file", Toast.LENGTH_SHORT).show();
return false;
}
if (inputStream == null) {
Toast.makeText(getActivity(), "File does not exist", Toast.LENGTH_SHORT).show();
return false;
}
try {
copyFile(inputStream, mSnapFile);
} catch (IOException e) {
Toast.makeText(getActivity(), "Failed save file locally", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
private static void copyFile(InputStream inputStream, File file) throws IOException {
byte[] buffer = new byte[1024];
int length;
try (FileOutputStream outputStream = new FileOutputStream(file)) {
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
}
}
Do not use ACTION_PICK as then the obtained uri is not valid anymore after restart.
Instead use ACTION_OPEN_DOCUMENT and take persistable uri permissions in onActivityResult.
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;
}
I have 3 menu buttons (add_image,save_meme and share_meme) on my action bar, which are declared in Mainactivity.java. The buttons are responsible for calling the corresponding methods in another fragment. The connection is established with LocalBroadcastManager.
public class MainActivity extends AppCompatActivity{
Intent saveIntent, shareIntent, addImageIntent;
LocalBroadcastManager localBroadcastManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
localBroadcastManager = LocalBroadcastManager.getInstance(getApplicationContext());
addImageIntent = new Intent("ADD_ACTION");
saveIntent = new Intent("SAVE_ACTION");
shareIntent = new Intent("SHARE_ACTION");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.add_image:
localBroadcastManager.sendBroadcast(addImageIntent);
case R.id.save_meme:
localBroadcastManager.sendBroadcast(saveIntent);
case R.id.share_meme:
localBroadcastManager.sendBroadcast(shareIntent);
default:
return super.onOptionsItemSelected(item);
}
}
}
As mentioned above, the corresponding methods are in the TopImageFragment.java class. The add_image button calls the method that allows the user to upload an image to the ImageView from the device:
public void selectedImage() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(intent, PICK_IMAGE);
}
The save_meme button calls the method that saves the bitmap to the device:
public void saveMeme(Bitmap btm) {
counter++;
File file;
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath();
file = new File(path + "/Memery/" + timeStamp + counter + ".jpg");
file.getParentFile().mkdir();
try {
OutputStream stream = new FileOutputStream(file);
btm.compress(Bitmap.CompressFormat.JPEG, 100, stream);
stream.flush();
stream.close();
Toast.makeText(getContext(), "Meme Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
Objects.requireNonNull(getContext()).sendBroadcast(mediaScanIntent);
}
The share_meme button calls the method that allows the user to share the meme on a variety of social media apps and email clients:
public void shareMeme(Bitmap bitmap) {
String path = MediaStore.Images.Media.insertImage(Objects.requireNonNull(getContext()).getContentResolver(), bitmap, "Meme", null);
Uri uri = Uri.parse(path);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
share.putExtra(Intent.EXTRA_TEXT, "This is my Meme");
getContext().startActivity(Intent.createChooser(share, "Share Your Meme!"));
}
But what's happening now is that whenever I select whichever of the 3 menu buttons, all 3 methods get called. This is my full fragment:
public class TopImageFragment extends Fragment {
ImageView imageView;
TextView topTextView, bottomTextView;
RelativeLayout topImageRelativeLayout;
public static final int PICK_IMAGE = 1;
Uri imageUri;
int counter = 0;
String timeStamp = new SimpleDateFormat("yyyyMMdd", Locale.CANADA).format(new Date());
float textSize, x, imageViewArea, canvasArea;
double val;
MemeViewModel memeViewModel;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_top_image, container, false);
imageView = view.findViewById(R.id.meme_image_view);
topTextView = view.findViewById(R.id.top_text_view);
bottomTextView = view.findViewById(R.id.bottom_text_view);
topImageRelativeLayout = view.findViewById(R.id.top_image_relative_layout);
if (savedInstanceState != null) {
imageUri = savedInstanceState.getParcelable("imageUri");
imageView.setImageURI(imageUri);
}
return view;
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("imageUri", imageUri);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
memeViewModel = ViewModelProviders.of(Objects.requireNonNull(getActivity())).get(MemeViewModel.class);
memeViewModel.getTopText().observe(getViewLifecycleOwner(), new Observer<CharSequence>() {
#Override
public void onChanged(#Nullable CharSequence charSequence) {
topTextView.setText(charSequence);
}
});
memeViewModel.getBottomText().observe(getViewLifecycleOwner(), new Observer<CharSequence>() {
#Override
public void onChanged(#Nullable CharSequence charSequence) {
bottomTextView.setText(charSequence);
}
});
}
public void selectedImage() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(intent, PICK_IMAGE);
}
public Bitmap getBitmap(ImageView img) {
BitmapDrawable bitmapDrawable = ((BitmapDrawable) img.getDrawable());
Bitmap bitmap = bitmapDrawable.getBitmap();
return bitmap.copy(Bitmap.Config.ARGB_8888, true);
}
public Bitmap screenshotMeme() {
Bitmap image = Bitmap.createBitmap(topImageRelativeLayout.getWidth(), topImageRelativeLayout.getHeight(), Bitmap.Config.RGB_565);
topImageRelativeLayout.draw(new Canvas(image));
return image.copy(Bitmap.Config.ARGB_8888, true);
}
public Bitmap drawMeme(Bitmap mutableBitmap) {
String topText = topTextView.getText().toString();
String bottomText = bottomTextView.getText().toString();
topText = topText.toUpperCase();
bottomText = bottomText.toUpperCase();
Canvas canvas = new Canvas(mutableBitmap);
TextPaint topFillPaint = new TextPaint();
TextPaint bottomFillPaint = new TextPaint();
TextPaint topStrokePaint = new TextPaint();
TextPaint bottomStrokePaint = new TextPaint();
Typeface typeface = getResources().getFont(R.font.impact);
textSize = topTextView.getTextSize();
imageViewArea = (imageView.getWidth()) * (imageView.getHeight());
canvasArea = (canvas.getWidth()) * (canvas.getHeight());
val = textSize * sqrt(canvasArea / imageViewArea);
x = (float) val;
topFillPaint.setColor(Color.WHITE);
topFillPaint.setTextSize(x);
topFillPaint.setTypeface(typeface);
topFillPaint.setStyle(Paint.Style.FILL_AND_STROKE);
topStrokePaint.setStyle(Paint.Style.STROKE);
topStrokePaint.setStrokeWidth(4);
topStrokePaint.setTextSize(x);
topStrokePaint.setColor(Color.BLACK);
topStrokePaint.setTypeface(typeface);
bottomFillPaint.setColor(Color.WHITE);
bottomFillPaint.setTextSize(x);
bottomFillPaint.setTypeface(typeface);
bottomFillPaint.setStyle(Paint.Style.FILL_AND_STROKE);
bottomStrokePaint.setStyle(Paint.Style.STROKE);
bottomStrokePaint.setStrokeWidth(4);
bottomStrokePaint.setColor(Color.BLACK);
bottomStrokePaint.setTextSize(x);
bottomStrokePaint.setTypeface(typeface);
StaticLayout topFillLayout = new StaticLayout(topText, topFillPaint, canvas.getWidth(), Layout.Alignment.ALIGN_CENTER,
0.8f, 0.0f, false);
StaticLayout topStrokeLayout = new StaticLayout(topText, topStrokePaint, canvas.getWidth(), Layout.Alignment.ALIGN_CENTER,
0.8f, 0.0f, false);
StaticLayout bottomFillLayout = new StaticLayout(bottomText, bottomFillPaint, canvas.getWidth(), Layout.Alignment.ALIGN_CENTER,
0.8f, 0.0f, false);
StaticLayout bottomStrokeLayout = new StaticLayout(bottomText, bottomStrokePaint, canvas.getWidth(), Layout.Alignment.ALIGN_CENTER,
0.8f, 0.0f, false);
topFillLayout.draw(canvas);
topStrokeLayout.draw(canvas);
canvas.translate(0, canvas.getHeight() - bottomFillLayout.getHeight());
bottomFillLayout.draw(canvas);
bottomStrokeLayout.draw(canvas);
return mutableBitmap;
}
public void saveMeme(Bitmap btm) {
counter++;
File file;
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath();
file = new File(path + "/Memery/" + timeStamp + counter + ".jpg");
file.getParentFile().mkdir();
try {
OutputStream stream = new FileOutputStream(file);
btm.compress(Bitmap.CompressFormat.JPEG, 100, stream);
stream.flush();
stream.close();
Toast.makeText(getContext(), "Meme Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
Objects.requireNonNull(getContext()).sendBroadcast(mediaScanIntent);
}
public void shareMeme(Bitmap bitmap) {
String path = MediaStore.Images.Media.insertImage(Objects.requireNonNull(getContext()).getContentResolver(), bitmap, "Meme", null);
Uri uri = Uri.parse(path);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
share.putExtra(Intent.EXTRA_TEXT, "This is my Meme");
getContext().startActivity(Intent.createChooser(share, "Share Your Meme!"));
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE) {
imageUri = Objects.requireNonNull(data).getData();
imageView.setImageURI(imageUri);
memeViewModel.setSharedId(imageUri.getLastPathSegment());
}
}
#Override
public void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(Objects.requireNonNull(getActivity())).registerReceiver(addListener, new IntentFilter("ADD_ACTION"));
LocalBroadcastManager.getInstance(Objects.requireNonNull(getActivity())).registerReceiver(saveListener, new IntentFilter("SAVE_ACTION"));
LocalBroadcastManager.getInstance(Objects.requireNonNull(getActivity())).registerReceiver(shareListener, new IntentFilter("SHARE_ACTION"));
}
private BroadcastReceiver addListener = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
selectedImage();
}
};
private BroadcastReceiver saveListener = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
float height = getBitmap(imageView).getHeight();
float width = getBitmap(imageView).getWidth();
if ((height <= 600) || (width <= 600)) {
saveMeme(screenshotMeme());
Toast.makeText(getContext(), "screenshotMeme() method was called", Toast.LENGTH_SHORT).show();
} else {
saveMeme(drawMeme(getBitmap(imageView)));
Toast.makeText(getContext(), "drawMeme() method was called", Toast.LENGTH_SHORT).show();
}
}
};
private BroadcastReceiver shareListener = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
float height = getBitmap(imageView).getHeight();
float width = getBitmap(imageView).getWidth();
if ((height <= 600) || (width <= 600)) {
shareMeme(screenshotMeme());
Toast.makeText(getContext(), "screenshotMeme() method was called", Toast.LENGTH_SHORT).show();
} else {
shareMeme(drawMeme(getBitmap(imageView)));
Toast.makeText(getContext(), "drawMeme() method was called", Toast.LENGTH_SHORT).show();
}
}
};
#Override
public void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(Objects.requireNonNull(getActivity())).unregisterReceiver(addListener);
LocalBroadcastManager.getInstance(Objects.requireNonNull(getActivity())).unregisterReceiver(saveListener);
LocalBroadcastManager.getInstance(Objects.requireNonNull(getActivity())).unregisterReceiver(shareListener);
}
}
Problem: Because in switch-case block, you do not return or put a break statement, then whenever a menu item is clicked, it will executes all statements in the switch-case.
Solution: Put a return true on each case to indicate you want consume the event when a menu item is clicked.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.add_image:
localBroadcastManager.sendBroadcast(addImageIntent);
return true;
case R.id.save_meme:
localBroadcastManager.sendBroadcast(saveIntent);
return true;
case R.id.share_meme:
localBroadcastManager.sendBroadcast(shareIntent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
or using a break statement on each case, then returning true at the end of method.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.add_image:
localBroadcastManager.sendBroadcast(addImageIntent);
break;
case R.id.save_meme:
localBroadcastManager.sendBroadcast(saveIntent);
break;
case R.id.share_meme:
localBroadcastManager.sendBroadcast(shareIntent);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
I'm trying to upload an image taken from the camera to the firebase storage, an message dialog appears but it keeps on charging and no images are uploaded to the storage.
Also I'd like to know, how can I get back the image sent from a specific user? should I give the image the user name to the image so I can get it back with his name?
public class ProfileActivity extends AppCompatActivity {
public static final int CAMERA_REQUEST = 10;
private LocationService service;
private Button uploadbtn;
private ImageView imgSpecimentPhoto;
private ImageView imgSpecimentPhoto2;
private ImageView imgSpecimentPhoto3;
private StorageReference storage;
private ProgressDialog mProgress;
Uri photoURI;
String mCurrentPhotoPath;
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 = getExternalFilesDir( Environment.DIRECTORY_PICTURES );
File image = File.createTempFile(
imageFileName,
".jpg",
storageDir
);
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent(){
Intent takePictureIntent = new Intent (MediaStore.ACTION_IMAGE_CAPTURE);
if(takePictureIntent.resolveActivity( getPackageManager())!= null){
//Create the file where the photo should go
File photoFile = null;
try{
photoFile = createImageFile();
}catch (IOException ex){
System.out.println("error taking the pic");
}
//Continue only if the file was successfull
if(photoFile != null){
photoURI = FileProvider.getUriForFile( this, "com.example.android.fileprovider",photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult( takePictureIntent, CAMERA_REQUEST );
}
}
}
private View currentView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile );
service = new LocationService(this);
uploadbtn = (Button) findViewById(R.id.upload);
storage = FirebaseStorage.getInstance().getReference();
mProgress = new ProgressDialog( this );
//get access to the image view
imgSpecimentPhoto = findViewById(R.id.camerabtn);
imgSpecimentPhoto2 = findViewById(R.id.camerabtn5 );
imgSpecimentPhoto3 = findViewById(R.id.camerabtn6);
uploadbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProgress.setMessage("Uploading...");
mProgress.show();
dispatchTakePictureIntent();
}
} );
}
public void checkPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
) {//Can add more as per requirement
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
123);
}
}
public void btnTakePhotoClicked(View v) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
System.out.println("first");
currentView= v;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
photoURI = data.getData();
//did the user chose okay
if(requestCode == CAMERA_REQUEST && resultCode == RESULT_OK){
//we are hearing back grom the camera
Bitmap cameraImage = (Bitmap) data.getExtras().get( "data" );
//now we have the image
ImageView cur = (ImageView) currentView;
cur.setImageBitmap( cameraImage );
if (cur.getId() == imgSpecimentPhoto.getId()) {
imgSpecimentPhoto2.setVisibility( View.VISIBLE );
}
if (cur.getId() == imgSpecimentPhoto2.getId()) {
imgSpecimentPhoto3.setVisibility( View.VISIBLE );
StorageReference filepath = storage.child("Photos").child( photoURI.getLastPathSegment());
filepath.putFile( photoURI).addOnSuccessListener( new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(ProfileActivity.this, "Upload Successfull", Toast.LENGTH_SHORT).show();
mProgress.dismiss();
}
} ).addOnFailureListener( new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText( ProfileActivity.this, "Upload Failed", Toast.LENGTH_SHORT).show();
}
} );
}
}
}}
when upload image on Firebase used below code ...
bearImage.setDrawingCacheEnabled(true);
bearImage.buildDrawingCache();
Bitmap bitmap = bearImage.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
// Upload it to our reference
UploadTask uploadTask = bearRef.putBytes(data);
buttonDownload.setEnabled(false);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
progressDialog.dismiss();
Log.w(LOG_TAG, "Upload failed: " + exception.getMessage());
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
Uri downloadUrl = taskSnapshot.getDownloadUrl();
progressDialog.dismiss();
Log.d(LOG_TAG, "Download Url: " + downloadUrl);
buttonDownload.setEnabled(true);
}
});
remove code for not need in above code..
About getting the image back with the username,
I would upload the photo in the storage with the following path:
// storage/photos/users/userID/photoName
StorageReference storageReference = FirebaseStorage
.getInstanace().getReference
.child("photos/users/" + user_id + "/photoName");
And then I would create a photos node in data base where I would add the userID and then the picture. Something like that:
In this specific case I am storing the user's profile photo into the database. ProfilePhoto model is just the profile image url.
ProfilePhoto profilePhoto = new ProfilePhoto(profile_img_url);
myRef.child("photos").child(user_id).child("photoName").setValue(profile_img_url);
By this way, when I want some user's photo I just get the link from database specifing the userID.
I have two activities, TakePictureActivity and ChoosePicActivity, and they both lead to PuzzleActivity.
As you can see, 1st activity starts an intent to start the camera, allows you to take a picture and starts the PuzzleActivity.
The 2nd activity accesses to the gallery, allows you to choose a picture and starts the PuzzleActivity.
In the PuzzleActivity the method createScaledBitmap is called to generate a bitmap.
Here is TakePictureActivity:
public class TakePictureActivity extends Activity {
String mCurrentPhotoPath;
static final int REQUEST_TAKE_PHOTO = 1;
public static final int DIALOG_PICASA_ERROR_ID = 0;
private static String DEBUG_TAG1 = "TakePictureA";
private Bitmap bitmap;
public static Uri imageUri;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.takepicture);
dispatchTakePictureIntent();
}
//TODO createImageFile
/* (non-Javadoc)
* Creates a file for the picture with a collision-resistant name using date-time stamp.
* Additionally, it saves the path to the picture in a member variable, mCurrentPhotoPath.
*/
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date(0));
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
Log.d(DEBUG_TAG1,"Current photo Path" + mCurrentPhotoPath);
galleryAddPic();
return image;
}
//TODO dispatchTakePictureIntent
/* (non-Javadoc)
* Starts an intent for the camera application.
*/
private void dispatchTakePictureIntent() {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (i.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
Log.d(DEBUG_TAG1,"try create iamge file");
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.d(DEBUG_TAG1,"error");
}
// Continue only if the File was successfully created
if (photoFile != null) {
Log.d(DEBUG_TAG1,"photo file not null");
i.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(i, REQUEST_TAKE_PHOTO);
}
}
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
#Override
protected final void onActivityResult(final int requestCode, final int resultCode, final Intent i) {
//super.onActivityResult(requestCode, resultCode, i);
if (resultCode == RESULT_OK) {
Log.d(DEBUG_TAG1,"TakePicture onActivityResult ");
switch (requestCode) {
case REQUEST_TAKE_PHOTO:
imageUri = i.getData();
Log.d(DEBUG_TAG1,"intent take pic: " + i);
Intent i1 = new Intent(this, PuzzleActivity.class);
startActivity(i1);
break;
} // end switch
} // end if
}
}
And here is ChoosePicActivity:
public class ChoosePicActivity extends Activity {
String mCurrentPhotoPath;
public static final int IMAGEREQUESTCODE = 8242008;
static final int REQUEST_TAKE_PHOTO = 1;
public static final int DIALOG_PICASA_ERROR_ID = 0;
private static String DEBUG_TAG1 = "ChoosePicA";
private Bitmap bitmap;
public static Uri imageUri;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
selectImageFromGallery();
}
/* (non-Javadoc)
* Will start an intent for external Gallery app.
* Image returned via onActivityResult().
*/
private void selectImageFromGallery() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, IMAGEREQUESTCODE);
}
//TODO onActivityResult
/* (non-Javadoc)
* Run when Gallery app returns selected image.
*/
#Override
protected final void onActivityResult(final int requestCode, final int resultCode, final Intent i) {
//super.onActivityResult(requestCode, resultCode, i);
if (resultCode == RESULT_OK) {
Log.d(DEBUG_TAG1,"ChoosePic onActivityResult ");
switch (requestCode) {
case IMAGEREQUESTCODE:
imageUri = i.getData();
Log.d(DEBUG_TAG1,"intent choose pic: " + i);
Intent i1 = new Intent(this, PuzzleActivity.class);
startActivity(i1);
break;
} // end switch
} // end if
}
}
And here is the PuzzleActivity:
public final class PuzzleActivity extends Activity implements OnClickListener{
private Bitmap bitmap; // temporary holder for puzzle picture
public static Chronometer chrono;
static TextView tv1;
static EditText et1;
Button button;
private static Context mContext;
//TODO onCreate
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.board);
mContext = this;
tv1 = (TextView) findViewById(R.id.movecount_display);
if(DecidePicActivity.choosepic){
try {
bitmap = createScaledBitmap(ChoosePicActivity.imageUri);
} catch (FileNotFoundException e) {
showDialog(DIALOG_PICASA_ERROR_ID);
} catch (IOException e) {
e.printStackTrace();
finish();
} catch (IllegalArgumentException e) {
showDialog(DIALOG_PICASA_ERROR_ID);
}
createGameBoard(getGridSize());
}
else if(DecidePicActivity.takepic){
try {
bitmap = createScaledBitmap(TakePictureActivity.imageUri);
} catch (FileNotFoundException e) {
showDialog(DIALOG_PICASA_ERROR_ID);
} catch (IOException e) {
e.printStackTrace();
finish();
} catch (IllegalArgumentException e) {
showDialog(DIALOG_PICASA_ERROR_ID);
}
createGameBoard(getGridSize());
}
TileView.moveDetector = new GestureDetectorCompat(this, new MyGestureListener());
Button pauseButton = (Button) findViewById(R.id.pause_button);
pauseButton.setOnClickListener(this);
}
The issue is:
I get to ChoosePicActivity, I choose a pic from the gallery, start intent to go to PuzzleActivity and creates the scaled bitmap with the chosen picture.
All good until here.
then, PuzzleActivity gets finished and i get to TakePictureActivity, camera starts, i take a pic, start intent to go PuzzleActivity and THEN the scaled bitmap generated uses the image previously chosen in the ChoosePicActivity, leaving the recently taken picture behind, which is the picture that it should have been used to generate the scaled bitmap.
On the other hand, if TakePictureActivity is started without ChoosePicActivity previously started, the taken picture is used to generate the scaled bitmap, as expected.
I hope I explained myself enough good for you to understand my problem. Could somebody give some light?
I'm not sure if having 2 times the method onActivityResult is correct, or if there are different threads conflicting, or maybe the method i.getdata() is having trouble to get the proper Intent id... I'm a bit lost.
The problem was caused by DecidePicActivity.choosepic and DecidePicActivity.takepic.
Previously, DecidePicActivity activity was like this:
public class DecidePicActivity extends Activity implements OnClickListener{
static boolean takepic = false;
static boolean choosepic = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.decidepic);
findViewById(R.id.take_pic_button).setOnClickListener(this);
findViewById(R.id.choose_pic_button).setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.take_pic_button:
takepic = true;
Intent i1 = new Intent(this, TakePictureActivity.class);
startActivity(i1);
break;
case R.id.choose_pic_button:
choosepic = true;
Intent i2 = new Intent(this, ChoosePicActivity.class);
startActivity(i2);
break;
}
}
}
takepic and choosepic they were not properly reinitialized.
Now onClick in DecidePicActivity activity is like this:
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.take_pic_button:
takepic = true;
choosepic = false;
Intent i1 = new Intent(this, TakePictureActivity.class);
startActivity(i1);
break;
case R.id.choose_pic_button:
choosepic = true;
takepic = false;
Intent i2 = new Intent(this, ChoosePicActivity.class);
startActivity(i2);
break;
}
}
and problem solved!