Encode in QRCode using ZXING - android

I'm trying to encode a String in QR Code wusing ZXING library. this is the lines of code corresponding to this :
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("com.google.zxing.client.android.ENCODE");
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.putExtra("ENCODE_TYPE", "TEXT_TYPE");
intent.putExtra("ENCODE_DATA","HELLO WORLD");
startActivityForResult(intent, 0);
}
});
}
After clicking on the button i have a "force close"
After looking in some websites, we say that it works just with these lines. unfortunately, it isnt for me.
PLEASE Can you give some advices to make it working. OR if you have other way to integrate a QRCode generator to my ANDROID App it will be great too.

Enzo, this is another way to get it working, try this:
private void encode(String uniqueID) {
// TODO Auto-generated method stub
BarcodeFormat barcodeFormat = BarcodeFormat.QR_CODE;
int width0 = 500;
int height0 = 500;
int colorBack = 0xFF000000;
int colorFront = 0xFFFFFFFF;
QRCodeWriter writer = new QRCodeWriter();
try
{
EnumMap<EncodeHintType, Object> hint = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
hint.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = writer.encode(uniqueID, barcodeFormat, width0, height0, hint);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++)
{
int offset = y * width;
for (int x = 0; x < width; x++)
{
pixels[offset + x] = bitMatrix.get(x, y) ? colorBack : colorFront;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
ImageView imageview = (ImageView)findViewById(R.id.qrCode);
imageview.setImageBitmap(bitmap);
} catch (WriterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

This line:
Intent intent = new Intent("com.google.zxing.client.android.ENCODE");
identifies the Activity you are calling with the Intent. In order for it to work that Activity must exist on the device. If you haven't implemented the Activity inside your project (that is, there is no class ENCODE inside your com.google.zxing.client.android package) then you will be calling an external application from yours. If there are no applications on the device/emulator that respond to the broadcast for com.google.zxing.client.android.ENCODE then you are not going to get anywhere with this solution.
You either need to install an application that will respond to com.google.zxing.client.android.ENCODE or find another way to do it.
It is possible to generate the barcode yourself using zxing libraries within your application. Have a look at the project here at Google Code for some downloads. This will remove your dependancy on an external application existing, providing a more thorough solution.

Rather than Zxing library you are also able to get the string from QRCode by using intents as below :
try {
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE"); // "PRODUCT_MODE for bar codes
startActivityForResult(intent, 0);
} catch (Exception e) {
Uri marketUri = Uri.parse("market://details?id=com.google.zxing.client.android");
Intent marketIntent = new Intent(Intent.ACTION_VIEW,marketUri);
startActivity(marketIntent);
}
And on activity result as below :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = data.getStringExtra("SCAN_RESULT");
Log.v("MESSAGE: ", contents);
Intent in = new Intent(MainActivity2.this,MainActivity3.class);
Bundle b3= new Bundle();
b3.putString("content",contents);
in.putExtras(b3);
startActivity(in);
}
}
}
It may be helpful for you.
Thank You.

Related

problem i'm getting (random order) after select images from gallery

after select multi images from gallery on order selection the images goes to the recycle view on random order not as I select on specific order or sort. for example if I select B then A then C but the code always bring them with random sort or order like A C B and sometimes C A B. . the order seems undefined at first I thought android sort them based on date and time added to the gallery or what their name i mean alphabet letter but then I realize the order seems undefined. i'm not sure if I need to add listener with array track the user selections. any suggestion
ArrayList imagesUriArrayList;
public static final int slect_photo = 100;
Bitmap bitmap1 = null;
RecyclerView rec;
LinearLayoutManager lnm;
Adopter_Browse list;
ArrayList<MyCard> mylist;
public void Onclick_View(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);//
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(intent, slect_photo);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (data.getData() != null) {//data.getData() != null) {
imagesUriArrayList = null;
imagesUriArrayList = new ArrayList();
try{
for (int i = 0; i < data.getClipData().getItemCount(); i++) {
imagesUriArrayList.add(data.getClipData().getItemAt(i).getUri());
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
}
try {
for (int i = 0; i < imagesUriArrayList.size(); i++) {
bitmap1 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), (Uri) imagesUriArrayList.get(i));
mylist.add(new MyCard(count_s, bitmap1));
}
} catch (IOException e) {
e.printStackTrace();
}
lnm = new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false);
list = new Adopter_Browse(mylist);
rec.setLayoutManager(lnm);
list.notifyDataSetChanged();
rec.setAdapter(list);
}
I found out that using onActivityResult that provided by google will always return the order of your selection on miss , so maybe a bug or need improve .
I got two option :
1- using ItemTouchHelper library ... helped me to solve my problem !
2- gradle source form githup !
I share this maybe some one can get relief !

Xamarin System Don't know about Android.Graphics.Bitmap

So i was trying to resize images with using android graphics bitmap. There is no error in code but when i build the project it throws out "System.NotSupportedException: Don't know about Android.Graphics.Bitmap" exception.
I tried ticking Common Language Runtime Exceptions and rebuilding the project both didnt work.
Here is my code
[Activity(MainLauncher = false, Theme = "#style/MyTheme")]
public class Duzenle_Activity : ActionBarActivity
{
public static ListView liw;
Intent intent = new Intent();
public Dialog dialog;
public static int toplam_hesap_tutucu;
public static Duzenle_Adapter adapt;
public static TextView toplam;
private BackgroundWorker bw = new BackgroundWorker();
public static int toplam_hesap = 0;
public List<Sepet> gecici_sepet;
List<Yemek_Liste> yemek_ = new List<Yemek_Liste>();
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.menu_duzenle);
var toolbar = FindViewById<Toolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolbar);
SupportActionBar.Title = "Duzenle";
yemek_ = MainActivity.db.selectItem();
liw = FindViewById<ListView>(Resource.Id.listv_duzenle);
adapt = new Duzenle_Adapter(this, Resource.Layout.duzenle_model, yemek_,this);
liw.Adapter = adapt;
var toolbarBottom = FindViewById<Toolbar>(Resource.Id.toolbar_bottom_duzenle);
toolbarBottom.InflateMenu(Resource.Menu.ekle_action);
toolbarBottom.MenuItemClick += (sender, e) =>
{
if (e.Item.TitleFormatted.ToString() == "Ekle")
{
var transaction = FragmentManager.BeginTransaction();
var dialogFragment = new Dialog_Ekle(this);
dialogFragment.Show(transaction, "dialog_fragment");
}
};
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (resultCode == Result.Ok)
{
Duzenle_Adapter adapter = ((Duzenle_Adapter)liw.Adapter);
Bitmap mBitmap = null;
mBitmap = Android.Provider.MediaStore.Images.Media.GetBitmap(ContentResolver, data.Data);
Bitmap originalImage = BitmapFactory.DecodeByteArray(mBitmap.ToArray<Byte>(), 0, mBitmap.ByteCount);
Bitmap resizedImage = Bitmap.CreateScaledBitmap(originalImage, 25, 25, false);
adapter.al_getir().adresler = resizedImage;
adapter.NotifyDataSetChanged();
Console.WriteLine("ADRES1" + " " + data.Data);
}
}
public void tikla()
{
var imageIntent = new Intent();
imageIntent.SetType("image/*");
imageIntent.SetAction(Intent.ActionGetContent);
StartActivityForResult(
Intent.CreateChooser(imageIntent, "Select photo"), 0);
}
}
And i get the image from gallery as uri.
Edit : Why is it throwing this exception when there is no error in code. Its actually strange. It cant be about the android.graphics library right?
Edit 2 : I save these bitmaps to database and then display it in listview
Bitmap a = sepet[position].adres;
tut.img.SetImageBitmap(a);
Based on what I got earlier from you please try this:
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (resultCode == Result.Ok)
{
Duzenle_Adapter adapter = ((Duzenle_Adapter)listView1.Adapter);
//adapter.SelectedYemek.ImageUri = data.Data;
var mBitmap = Android.Provider.MediaStore.Images.Media.GetBitmap(ContentResolver, data.Data);
adapter.SelectedYemek.ImageBitmap = Bitmap.CreateScaledBitmap(mBitmap, 80, 80, false);
adapter.NotifyDataSetChanged();
}
}

How to check imageview is empty or not where imageview created programmatically in android

I created image view programatically, and need check image view is empty or not.
getdrawable(),getHeigt() and getwidth() methodes but it is not working for me.
Imageview created like this:
ImageView iv = new ImageView(this);
code:
public void dynamicTable(String alist[]) throws NullPointerException {
try {
TableLayout tl = (TableLayout) findViewById(R.id.main_table1);
tl.setBackgroundColor(Color.GRAY);
sizelen = alist.length;
cam = new Button[sizelen];
iv = new ImageView[sizelen];
int k;
for (k = 0; k < sizelen; k++) {
try {
final int j = k;
TableRow tr_head = new TableRow(this);
TableLayout.LayoutParams rowparams = new TableLayout.LayoutParams(
TableLayout.LayoutParams.FILL_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT);
int leftMargin = 2;
int topMargin = 1;
int rightMargin = 2;
int bottomMargin = 1;
rowparams.setMargins(leftMargin, topMargin, rightMargin,
bottomMargin);
rowparams.weight = (float) 0.5;
tr_head.setLayoutParams(rowparams);
// tr_head.setId(10);
tr_head.setBackgroundColor(Color.WHITE);
/*
* tr_head.setLayoutParams(new LayoutParams(
* LayoutParams.FILL_PARENT LayoutParams.WRAP_CONTENT));
*/
cam[k] = new Button(this);
cam[k].setText(alist[k]);
cam[k].setTextColor(Color.WHITE);
cam[k].setBackgroundColor(Color.parseColor("#ffab00"));
cam[k].setClickable(true);
cam[k].setFocusable(true);
cam[k].setGravity(Gravity.LEFT);
cam[k].setMaxLines(2);
cam[k].setPadding(10, 10, -10, 10);
cam[k].setAllCaps(false);
cam[k].setTextSize(13);
cam[k].setLayoutParams(new TableRow.LayoutParams(85,
TableLayout.LayoutParams.WRAP_CONTENT));
// cam[i].setWidth(150);
// cam[i].setEms(0);
// cam[i].setGravity(25);
// cam[i](Gravity.LEFT);
// cam[i].setLayoutParams(params);
cam[k].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cam[j].setBackgroundColor(Color.GRAY);
camera(j);
}
});
tr_head.addView(cam[k]); // add the column to the table row
// here
iv[k] = new ImageView(this);
iv[k].setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT));
iv[k].setPadding(0, 7, 10, 0);
iv[k].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
imageviewOnclick(iv[j]);
}
});
tr_head.addView(iv[k]); // dd the column to the table row
// here
tl.addView(tr_head, rowparams);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
These methods will take the photo from the phone and display it in an ImageView, i guess you can use this in your code to see if the photo shows up or not.
public void DisplayPhotoPreview(){
DisplayPhotoPreview = (Button)findViewById(R.id.UploadPhotoPreviewBtn);//Finds the button in design and put it into a button variable.
DisplayPhotoPreview.setOnClickListener(//Listens for a button click.
new View.OnClickListener() {//Creates a new click listener.
#Override
public void onClick(View v) {//does what ever code is in here when the button is clicked
switch (v.getId()) {//switches to the case if that .id. is clicked.
case R.id.UploadPhotoPreviewBtn://Does what ever the code is in the case if the upload button is clicked.
//I open up an intent variable and through different commands and I open up my gallery on my phone and i cant get
//out of the gallery until i choose a photo. Then I save the photo in the intent and call the onActivityResult() method which displays the image.
//Also a intent is how two activities can send data.
Intent ChoosePhotoFromGallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(ChoosePhotoFromGallery, RESULT_LOAD_IMAGE);//Stores the image into the variable.
break;
}
}
}
);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//so the if statement checks if the image came through, double checks if the result is okay and triple checks to see if the data is not null.
if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null){
//gets the address of the image/data !!!!!!ALSO CAN HOLD THE ADDRESS FOR THE SERVER!!!!!!.
Uri Image = data.getData();
ItemPhotoPreview = (ImageView)findViewById(R.id.ItemPhotoPreviewImageView);
//Sets the image into the variable and displays it
ItemPhotoPreview.setImageURI(Image);
}
}

Error in creating image of barcode in Android Studio

I want to create the image of the barcode/QR code etc on my app. I have searched a lot and have found different libraries to do this task but since I am already using Zxing so i would like to work in it.
Following is the code that I have writen:
This is my Scanner Activity class:
public void handleResult(Result rawResult) {
// Do something with the result here
Log.v(TAG, rawResult.getText()); // Prints scan results
Toast.makeText(SimpleScannerActivity.this, rawResult.toString() + " WOW scanned", Toast.LENGTH_LONG).show();
Toast.makeText(SimpleScannerActivity.this, rawResult.getBarcodeFormat().toString(), Toast.LENGTH_LONG).show();
Log.v(TAG, rawResult.getBarcodeFormat().toString()); // Prints the scan format (qrcode, pdf417 etc.)
//Intent scanScreenResult= new Intent("com.aaa.fyp.ScanResultScreen");
setFormat(rawResult);
Intent nextScreen = new Intent("com.aaa.fyp.ScanResultScreen");
nextScreen.putExtra("barcode",rawResult.toString());
nextScreen.putExtra("format", rawResult.getBarcodeFormat().toString());
finish();
startActivity(nextScreen);
}
public void setFormat(Result result){
r=result.getBarcodeFormat();
System.out.println("============================== setformat main"+ r);
}
public BarcodeFormat getFormat(){
System.out.println("============================== getformat main"+ r);
return r;
}
Using the results from the above activity in ScanResultScreen activity.
public class ScanResultScreen extends SimpleScannerActivity {
ImageView scanned;
TextView bc;
TextView f;
String Barcode;
String format;
BarcodeFormat form;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.scan_screen_with_button);
ViewGroup layout = (ViewGroup) findViewById(R.id.scanScreenWithButton);
setContentView(layout);
Intent prevScreen = getIntent(); // gets the previously created intent
Barcode=prevScreen.getStringExtra("barcode");
bc= (TextView)findViewById(R.id.barcode_label);
bc.setText(Barcode);
format=prevScreen.getStringExtra("format");
f=(TextView) findViewById(R.id.format_label);
f.setText(prevScreen.getStringExtra("format").toString());
SimpleScannerActivity obj=new SimpleScannerActivity();
form=obj.getFormat();
d=(TextView)findViewById(R.id.date_label);
String formattedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
d.setText(formattedDate);
Bitmap bitmap = null;
ImageView iv = new ImageView(this);
try {
bitmap = encodeAsBitmap(Barcode, form, 600, 300);
iv.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
layout.addView(iv);
}
private static final int WHITE = 0xFFFFFFFF;
private static final int BLACK = 0xFF000000;
Bitmap encodeAsBitmap(String contents, BarcodeFormat format, int img_width, int img_height) throws WriterException {
String contentsToEncode = contents;
if (contentsToEncode == null) {
return null;
}
Map<EncodeHintType, Object> hints = null;
String encoding = guessAppropriateEncoding(contentsToEncode);
if (encoding != null) {
hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, encoding);
}
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix result;
try {
result = writer.encode(contentsToEncode, format, img_width, img_height, hints);
} catch (IllegalArgumentException iae) {
// Unsupported format
return null;
}
int width = result.getWidth();
int height = result.getHeight();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
private static String guessAppropriateEncoding(CharSequence contents) {
// Very crude at the moment
for (int i = 0; i < contents.length(); i++) {
if (contents.charAt(i) > 0xFF) {
return "UTF-8";
}
}
return null;
}
Now I am getting a Null value in the variable "form". Even though I am able to get the barcodeFormat in my second activity by passing it through intent but it's in the type String. Whereas the built-in methods that I am using here requires it in BarcodeFormat that is available in Zxing.
Help!!
BarcodeFormat is an enum type. If you want to pass a String value, you have to convert it to BarcodeFormat.
For example, passing a barcode format "AZTEC":
BarcodeFormat format = Enum.valueOf(BarcodeFormat.class, "AZTEC");

How to create a QR code for my existing android application?

I want to create a QR code for my existing Android application (built in Android Studio). I need to get some ID's from the back end & generate the QR code then view it in my layout.
Please help me.
Here are some of my sample codes, you can refer, some values may be different depend on the mobile phone model. Hope this help! I use zxing library.
private void startScan(Context context, String parameter) {
Intent intent = new Intent();
intent.setAction("com.motorolasolutions.emdk.datawedge.api.ACTION_SOFTSCANTRIGGER");
intent.putExtra("com.motorolasolutions.emdk.datawedge.api.EXTRA_PARAMETER", parameter);
context.sendBroadcast(intent);
}
#Override
public boolean onKeyUp(int keyCode, #NonNull KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_UP) && keyCode == KeyEvent.KEYCODE_...) {
startScan(this, "START_SCANNING");
registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String code = intent.getExtras().getString("com.motorolasolutions.emdk.datawedge.data_string");
ImageView imageView = (ImageView) findViewById(R.id.imageView);
TextView textView = (TextView) findViewById(R.id.textView);
if ((imageView != null) && (textView != null)) {
textView.setText(code);
// barcode image
try {
mBarCodeBitmap = encodeBarCodeAsBitmap(value, BarcodeFormat.CODE_128, 200, 100);
imageView.setImageBitmap(mBarCodeBitmap);
} catch (WriterException e) {
}
}
unregisterReceiver(this);
}
}, new IntentFilter("com.example.SoftScanIntentAction")); // this value must be set in DataWedge profile (Intent Output - Intent action...)
}
return super.onKeyUp(keyCode, event);
}
private Bitmap encodeBarCodeAsBitmap(String contents, BarcodeFormat format, int width, int height) throws WriterException {
String contentsToEncode = contents;
if (contentsToEncode == null) {
return null;
}
Map<EncodeHintType, Object> hints = null;
String encoding = guessAppropriateEncoding(contentsToEncode);
if (encoding != null) {
hints = new EnumMap<>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, encoding);
}
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix result;
try {
result = writer.encode(contentsToEncode, format, width, height, hints);
} catch (IllegalArgumentException iae) {
// Unsupported format
return null;
}
int imgWidth = result.getWidth();
int imgHeight = result.getHeight();
int[] pixels = new int[imgWidth * imgHeight];
for (int y = 0; y < imgHeight; y++) {
int offset = y * imgWidth;
for (int x = 0; x < imgWidth; x++) {
pixels[offset + x] = result.get(x, y) ? 0xFF000000 : 0xFFFFFFFF;
}
}
Bitmap bitmap = Bitmap.createBitmap(imgWidth, imgHeight,
Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, imgWidth, 0, 0, imgWidth, imgHeight);
return bitmap;
}

Categories

Resources