I tried all examples both from the docs and from online help, but I can't get a simple image I have in the storage to display on an image view.
assuming I have pictures in the storage in a folder called pictures so photo1.jpg is stored in the reference:
StorageReference storageReference = FirebaseStorage.getInstance().getReference();
StorageReference photoReference= storageReference.child("pictures/photo1.jpg");
But how do I set it and replace the contents with an existing image view that I find by id:
ImageView photoView= (ImageView) findViewById(R.id.photo_view);
I keep getting failure on the listener to get Uri:
storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
profileImage.setImageURI(uri);
Log.d("Test"," Success!");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.d("Test"," Failed!");
}
});
Using below code you can set image on ImageView:
StorageReference storageReference = FirebaseStorage.getInstance().getReference();
StorageReference photoReference= storageReference.child("pictures/photo1.jpg");
final long ONE_MEGABYTE = 1024 * 1024;
photoReference.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
#Override
public void onSuccess(byte[] bytes) {
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
imageView.setImageBitmap(bmp);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(getApplicationContext(), "No Such file or Path found!!", Toast.LENGTH_LONG).show();
}
});
You can use the Uri as well, for that you need to save the byte array to a file. Use below code for the same:
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.jpg");
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
// remember close de FileOutput
fo.close();
There may be something going wrong with the uri you have retrieved from the Firebase Storage, try putting it on log, like this:
Log.d("uri:",uri.toString());
This may give you a hint, what is going wrong with retrieving the value. If you choose to use Glide or Picasso, then do refer their GitHub pages from the links above, and see what you need.
Using Glide and Picasso both is simple, and here's an example of how to use Glide to store the images in your imageView.
// Reference to an image file in Cloud Storage
StorageReference storageReference = = FirebaseStorage.getInstance().getReference().child("yourImageReferencePath");
ImageView image = (ImageView)findViewById(R.id.imageView);
// Load the image using Glide
Glide.with(this /* context */)
.using(new FirebaseImageLoader())
.load(storageReference)
.into(image );
If you don't want to use any external library and want to retrieve the image, then do refer this answer, it might help.
Try to get the download URL of the image that you have uploaded in the database and use Picasso or GLIDE library to load it into the imageview you desire.
Related
I would like to enter multiple text fields for example
name
email
password
address
And then I would like to generate a QR code from this input. How can I do that in android studio?
Setting up the library and manifest
Open App level gradle file and import the library.
implementation 'androidmads.library.qrgenearator:QRGenearator:1.0.3'
The, click “Sync Now”.
Then, open your Manifest file and add the following permissions. It is used to save QR Code to file storage.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
We need to handle runtime permissions from Android Version 6.0.
Generating QR Code
QRGEncoder qrgEncoder = new QRGEncoder(inputValue, null, QRGContents.Type.TEXT, smallerDimension);
Here, inputValue is an input to be converted to QR Code.
Input Type also can be specified while initializing the library.
We can specify the dimensions also.
Then, add the following lines to create QR Code and encode that into Bitmap Format.
try {
// Getting QR-Code as Bitmap
bitmap = qrgEncoder.encodeAsBitmap();
// Setting Bitmap to ImageView
qrImage.setImageBitmap(bitmap);
} catch (WriterException e) {
Log.v(TAG, e.toString());
}
qrImage is an ImageView used to preview the generated QR code bitmap.
Saving QR Code
QR Generator has an option to save the generated QR Code Bitmap to storage using the following lines.
// Save with location, value, bitmap returned and type of Image(JPG/PNG).
QRGSaver.save(savePath, edtValue.getText().toString().trim(), bitmap, QRGContents.ImageType.IMAGE_JPEG);
We can save QR Code in PNG & JPG format also. We have to handle runtime permissions from Android version 6.0.
Your particular case:
Combine the information you want to encode in the QR code, and add it as the inputValue for the QRGEncoder. Here is an example code for clarity:
public class MainActivity extends AppCompatActivity {
String TAG = "GenerateQRCode";
EditText edtValue;
ImageView qrImage;
Button start, save;
String inputValue;
String savePath = Environment.getExternalStorageDirectory().getPath() + "/QRCode/";
Bitmap bitmap;
QRGEncoder qrgEncoder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
qrImage = (ImageView) findViewById(R.id.QR_Image);
edtValue = (EditText) findViewById(R.id.edt_value);
start = (Button) findViewById(R.id.start);
save = (Button) findViewById(R.id.save);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
inputValue = edtValue.getText().toString().trim();
if (inputValue.length() > 0) {
WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
Point point = new Point();
display.getSize(point);
int width = point.x;
int height = point.y;
int smallerDimension = width < height ? width : height;
smallerDimension = smallerDimension * 3 / 4;
qrgEncoder = new QRGEncoder(
inputValue, null,
QRGContents.Type.TEXT,
smallerDimension);
try {
bitmap = qrgEncoder.encodeAsBitmap();
qrImage.setImageBitmap(bitmap);
} catch (WriterException e) {
Log.v(TAG, e.toString());
}
} else {
edtValue.setError("Required");
}
}
});
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean save;
String result;
try {
save = QRGSaver.save(savePath, edtValue.getText().toString().trim(), bitmap, QRGContents.ImageType.IMAGE_JPEG);
result = save ? "Image Saved" : "Image Not Saved";
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Article: https://www.c-sharpcorner.com/article/how-to-generate-qr-code-in-android/
Concatenate all the information in a string and do a hash on said string. Next use a library such as (https://github.com/zxing/zxing) to generate the QR code.
Use this for generating qr code online. Then use picasso to load the image. ( Use your data in the url parameter )
https://chart.googleapis.com/chart?chs=500x500&cht=qr&chl=data
I found it as the best way.
I need to set image to my image view
For this reason I use Picasso library
Here is approach how I do this
File image = new File("file:" + path);
Picasso.with(context)
.load(image)
.placeholder(R.drawable.progress_animation)
.error(R.drawable.image_error_404)
.into(iv);
and also I tried the same without prefix file: like here
File image = new File(path);
Picasso.with(context)
.load(image)
.placeholder(R.drawable.progress_animation)
.error(R.drawable.image_error_404)
.into(iv);
But all the time I got image from .error() ,
There is a path with file: prefix - "file:/storage/emulated/0/Android/data/com.fittingroom.newtimezone/files/default/AvatarPackage/DEFAULT_MY_AVATAR/pose1.jpeg"
and there is path witout file: prefix - "/storage/emulated/0/Android/data/com.fittingroom.newtimezone/files/default/AvatarPackage/DEFAULT_MY_AVATAR/pose1.jpeg"
Anyway I got no result
Why picasso doesn't want to set my image
What am I doing wrong?
Your path prefix is incorrect: use file:/// instead of file:
Thanks #CommonsWare I solve my issue such way
.fit()
.centerInside()
And here is my implementation
File image = new File(path);
Picasso picasso = new Picasso.Builder(context)
.listener(new Picasso.Listener() {
#Override public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
Logger.logError("ERROR Download image: ", exception, context);
}
}).build();
picasso
.load(image)
.fit()
.centerInside()
.placeholder(R.drawable.progress_animation)
.error(R.drawable.image_error_404)
.into(iv, new Callback() {
#Override public void onSuccess() {
Logger.logGeneral("image downloaded");
}
#Override public void onError() {
Logger.logGeneral("onError image downloaded");
}
});
I'm building a profile page for my app. I've made it in such a way that tapping on the previous profile image, the user will be able to change its profile picture. I would like that after the upload, the profile picture will be instantaneously updated. I've tried using Picasso but it seems to have some problems with the cache. In fact after the user has chosen his image, the picture which is shown is the same as before, despite the fact that the app overwrites the previous image file and re-apply Picasso. I'm using Android API 22.
Profile.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
ImageView pic = (ImageView) findViewById(R.id.picc);
...
String root = Environment.getExternalStorageDirectory().toString();
String path = root + "/directory/name.jpg";
MainActivity.trimCache(this);
Picasso.with(getApplicationContext()).load(path)
.networkPolicy(NetworkPolicy.NO_CACHE)
.memoryPolicy(MemoryPolicy.NO_CACHE)
.transform(new RoundedTransformation(1000, 0))
.resize(500, 500)
.centerCrop()
.into(pic);
}
pic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent chooseImageIntent = ImagePicker.getPickImageIntent(getApplicationContext());
startActivityForResult(chooseImageIntent, PICK_IMAGE_ID);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap bitmap = ImagePicker.getImageFromResult(this, resultCode, data);
ImageView pic = (ImageView) findViewById(R.id.picc);
RetrieveFeedTask job = new RetrieveFeedTask(data, resultCode, this, bitmap);
job.execute("user","pass");
String root = Environment.getExternalStorageDirectory().toString();
String path = root + "/directory/name.jpg";
MainActivity.trimCache(this);
Picasso.with(getApplicationContext()).load(path)
.networkPolicy(NetworkPolicy.NO_CACHE)
.memoryPolicy(MemoryPolicy.NO_CACHE)
.transform(new RoundedTransformation(1000, 0))
.resize(500, 500)
.centerCrop()
.into(pic);
}
ImagePicker.java is a standard image picker file.
I've also tried to delete the cache from the app with the following function
public static void trimCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
// TODO: handle exception
}
}
The Picasso instance, by default, holds a memory cache. Picasso sees the same key for the cache (the path in this case) and just simply returns the Bitmap instance from the cache that it gets from that key.
You have the right thing there with memoryPolicy(MemoryPolicy.NO_CACHE) to skip the cache check; are you sure that's the way you are calling for the image after the change/update?
how to make users to download the image in the listview onclick of the list item.The images are from drawable folder, not from the web?
if you are referring to saving images to your phone, from your drawable folder.you should check this link out.
How to save a bitmap image with imageview onclick
it says how to save an image from the app to your phone
To get bitmap from imageview:
imageview.buildDrawingCache();
Bitmap bm=imageview.getDrawingCache();
To save it in a file:
OutputStream fOut = null;
Uri outputFileUri;
try {
File root = new File(Environment.getExternalStorageDirectory() + File.separator + "folder_name" + File.separator);
root.mkdirs();
File sdImageMainDirectory = new File(root, "myPicName.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
fOut = new FileOutputStream(sdImageMainDirectory);
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
}
give this inside the listview on click
You can store your images id in an int[] integer array like this:
int[] myImages = {R.drawable.myfirstimage,R.drawable.mysecondimage};
and add to your listView an onItemClick method where you change your corresponding ImageView based on the position of the item clicked
myListview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ImageView imageView = (ImageView) view.findViewById(R.id.myImageView);
imageView.setBackgroundResource(myImages[position]);
}
});
In my application I will receive a byte stream and convert it to a pdf file in the phone memory. How do I render that to a pdf? And show it on an activity?
Some phones (like the Nexus One) come with a version of Quickoffice pre-installed so it may be as easy as sending the appropriate Intent once you've saved the file to the SD card.
public class OpenPdf extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.OpenPdfButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File file = new File("/sdcard/example.pdf");
if (file.exists()) {
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
Toast.makeText(OpenPdf.this,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
Open pdf file in webview.
public class MyPdfViewActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView mWebView=new WebView(MyPdfViewActivity.this);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginsEnabled(true);
mWebView.loadUrl("https://docs.google.com/gview?embedded=true&url="+LinkTo);
setContentView(mWebView);
}
}
Android-Lollipop (api 21) introduce a new API : PdfRenderer
This API allows you to create a Bitmap from a page in a PDF document.
Shortly :
get a seekable file descriptor from your pdf document :
ParcelFileDescriptor fd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
create the PdfRenderer
PdfRenderer renderer = new PdfRenderer(fd);
prepare the Bitmap
Bitmap bitmap = Bitmap.createBitmap(WIDTH, HEIGHT, Bitmap.Config.ARGB_4444);
get the PdfRenderer.Page to render
PdfRenderer.Page page = renderer.openPage(pageIndex);
render the page on the prepared bitmap
page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
now you can do what you want with the bitmap.
note that the 2 null args may allow you to clip some portion in the page and perform a transformation (using a Matrix) of the clip
there is another rendering mode : RENDER_MODE_FOR_PRINT. If you need this mode there are some guidelines to use it properly : here are the details.
This library is simple and works well:
Android Pdf Viewer
https://github.com/barteksc/AndroidPdfViewer
Old Reply...
I think that Joan Zapata give us the better and simple solution:
https://github.com/JoanZapata/android-pdfview
I assure you that it works!
1: https://github.com/JoanZapata/android-pdfview
For the local pdf files, you can render them through the third party libraries. for example, use the MuPDF library, its supported file types include PDF, PNG and JPEG.
One shortcoming of MuPDF is that it uses native library to fulfill the target, so it won't be easy to port the application on BlackBerry platform later.
To open a pdf from a byte array, you can use RadaeePDF, you can do the following into your activity:
private PDFReader m_vPDF = null;
private Document doc = new Document();
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Global.Init(this);
m_vPDF = new PDFReader(this);
doc.Close();
int ret = m_doc.OpenMem(data, password);
switch( ret )
{
case -1://need input password
finish();
break;
case -2://unknown encryption
finish();
break;
case -3://damaged or invalid format
finish();
break;
case -10://access denied or invalid file path
finish();
break;
case 0://succeeded, and continue
break;
default://unknown error
finish();
break;
}
m_vPDF.open(doc);
setContentView( m_vPDF );
}