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.
Related
I am trying desperately to read a file from Android Studio asset folder. The file is "ok.txt" and contains the string: yo chicken mcgriddle fiddle fiddle.
Per this video: https://youtu.be/1CHDASXojNQ and stackoverflow browsing, this is the solution I came up with:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
tv_text = (TextView) findViewById(R.id.nameView);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
tv_text.setText(LoadData("ok.txt"));
}
public String LoadData(String inFile) {
String tContents = "";
try {
InputStream stream = getAssets().open(inFile);
int size = stream.available();
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
tContents = new String(buffer);
} catch (IOException e) {
// Handle exceptions here
}
return tContents;
}
});
}
}
I am inclined to believe that the code works, but, it does not return the String. In the app, it returns a blank message in the place of the textview's "hello world" placeholder after clicking the button. I thought it was due to the limitation of the textview so I modified the constraint size, but the blank persists. Anybody know what's up?
I'm trying to use an Activity which displays a random object from my array. This object is passed in from an intent.
I am trying to use an image for each of these objects and then display the correct image for the correct object.
So far I've been using the drawable folder to hold my images and then loading them in through the XML however this stops me using multiple images for the same ImageView.
I tried using imageview.setImageResource(R.drawable.imagename); but that doesn't seem to like loading in for some reason.
Do I need to make a new activity for each of the objects in this case?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_random_race);
TextView name = (TextView)findViewById(R.id.raceName);
Intent secondIntent = getIntent();
Race message = (Race)secondIntent.getSerializableExtra("RACE");
ImageView image = (ImageView) findViewById(R.id.raceImage);
image.setImageResource(R.drawable.hacan);
image.setImageBitmap(imageToBitmapImage(message, image));
name.setText(message.getName());
}
Bytes to Bitmap method
public Bitmap imageToBitmapImage (Race message, ImageView image){
Bitmap bmp;
try {
FileInputStream in = new FileInputStream(message.getImageName());
BufferedInputStream buffer = new BufferedInputStream(in);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int input = buffer.read();
while (input != -1){
baos.write(input);
input = buffer.read();
}
byte[] bytes = baos.toByteArray();
bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
return bmp;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Class of each object I'm talking about.
public class Race implements Serializable {
private String name;
private String imageName; //name of file within drawable
As #XavierFalempin commented, you can't access ressources through a file stream. Using setImageResource() should work. Following this answer your onCreate() method should look something like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_random_race);
TextView name = (TextView)findViewById(R.id.raceName);
Intent secondIntent = getIntent();
Race message = (Race)secondIntent.getSerializableExtra("RACE");
ImageView image = (ImageView) findViewById(R.id.raceImage);
image.setImageResource(getResources().getIdentifier(message.getImageName(),
"drawable",
getPackageName()));
name.setText(message.getName());
}
I am pretty new to Android development and I'm trying to figure out how to tap an image in my app and save it to the device. When the image is tapped I want a Save button to appear and when that is pressed, a toast should appear saying the picture was saved. On iOS I am able to do this with UIActionSheet.
I should also mention that the image view image is downloaded from a URL using Picasso.
I just tried this and it says the image saved but when I go to the photos app on my phone, the image is not there.
largeImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveButton.setVisibility(View.VISIBLE);
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
largeImage.getDrawable();
Bitmap bitmap = ((BitmapDrawable)largeImage.getDrawable()).getBitmap();
OutputStream outStream = null;
File file = new File(storageDirectory, "er.PNG");
try {
outStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
Toast.makeText(FlickrImageActivity.this, "Saved", Toast.LENGTH_LONG).show();
}
catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(FlickrImageActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
catch (IOException e) {
e.printStackTrace();
Toast.makeText(FlickrImageActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
saveButton.setVisibility(View.GONE);
}
});
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Manifest permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You can use RelativeLayout to contain a ImageView and a Button.
Align both of them center in parent
inside the activity, set the button visibility to "gone"
call setOnClickListener of the ImageView and Button to your Activity
implement OnClickListener in your Activity
inside onClick(View v), if the view clicked is the ImageView, set the visibility of Button to "visible"
inside onClick(View v), if the view clicked is the Button, save the image to disk
** how to save image to disk
if the image source is drawable resources, use BitmapFactory.decodeResource to create a Bitmap then use Bitmap.compress to export to a specific path
specific path is recommended to be obtained from Environment.getExternalStoragePublicDirectory
then notify the Android to refresh gallery
MediaScannerConnection.scanFile(context,
new String[] { imagePath }, null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
//....
}
});
Then use a Toast.makeText(context, "message here").show(); to show the message to user
See below steps to acheive this in Android :
1. Create layout with ImageView & 'Save' named Button
2.By deafult set 'Save' Button's visibility = gone/invisible
3. Apply click listener on both the views (ImageView & Button)
4. OnClick of ImageView, set 'Save' Button's visibility = visible
5. onclick of save button click call your save image to sdcard logic. Check below link for that.
http://android-er.blogspot.in/2010/07/save-file-to-sd-card.html
Hope this will help you.
I am experimenting with the android FaceDetector.
I need to use a bitmap file (faces.bmp is from a group photo) since I have not found a way to use the android camera in the android emulator.
But BitmapFactory.decodeFile returns null and the documentation only says it returns null if the bitmap could not be decoded. It is just a 24 bit .bmp file. I am using Eclipse on Windows 7. Did I specify pathName incorrectly? Do I need to use something other than a 24 bit .bmp file?
public class MyFaces extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final int width = 600;
final int height = 600;
final int maxFaces = 8;
FaceDetector faceDetector = new FaceDetector(width, height, maxFaces);
String pathName = "../res/drawable-hdpi/faces.bmp";
try {
Bitmap bitmap = BitmapFactory.decodeFile(pathName);
Face faces[] = new Face[maxFaces];
int nFaces = faceDetector.findFaces(bitmap, faces);
Log.d(this.getClass().toString(), "Faces: " + nFaces);
} catch (Exception e) {
Log.e(this.getClass().toString(), e.getMessage(), e);
}
}
}
If you are just testing then in place of Bitmap bitmap = BitmapFactory.decodeFile(pathName); you could use:
Bitmap bitmap = BitmapFactory.decodeResource(R.drawable.faces);
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 );
}