How to Generate QR Code in Android App

In our previous post, we learned how to scan and decode the QR Code in our own Android app.

Today, we are going to learn how to generate QR Code in our own Android App.

Now Let’s Dive into the learning process 🙂

1. To integrate Zxing library

Please refer to How to Implement QR Code Scanner in Android to learn how to integrate Zxing library for QR Code encoding and decoding.

2. Creating layout

Open layout file for your Activity, e.g. activity_main.xml and add the following lines:

<EditText
       android:layout_width="match_parent"
       android:layout_height="25dp"
       android:layout_below="@id/btnClick"
       android:layout_marginTop="25dp"
       android:id="@+id/txtEncode"
       android:hint="Enter text"
       />

   <Button
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_below="@id/btnClick"
       android:text="Encode"
       android:id="@+id/btnEncode"
       />

The EditText is used to enter the text to be encoded and Button is used to handle the user input.

3. Handling the click event of Button

Open MainActivity.java file and add the following lines:

final EditText etEncode = (EditText) findViewById(R.id.txtEncode);

        Button btnEncode = (Button) findViewById(R.id.btnEncode);
        btnEncode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String data=etEncode.getText().toString();
                Intent intent = new Intent(MainActivity.this, EncodeActivity.class);
                intent.setAction(Intents.Encode.ACTION);
                intent.putExtra(Intents.Encode.TYPE, Contents.Type.TEXT);
                intent.putExtra(Intents.Encode.DATA,data);
                startActivity(intent);
            }
        });

We are just calling the EncodeActivity of Zxing library to Encode and Display the QR Code generated from the data passed in the Intent.

4. Let’s run the Application

You have just created your own QR Code Encoding and Decoding Application 🙂