Using ViewSwitcher in Android

Hello friends!

A ViewSwitcher as the name suggests is used to switch between two views. It is used to change the layout of your Android application within the same Activity. You can create views for a ViewSwitcher widget either using a factory or by adding them on your own. As mentioned on the Android developer’s page, a ViewSwitcher can only have two child views, of which only one is shown at a time.

Through this post, we will learn how to use the ViewSwitcher widget in Android. It is important note that both ViewSwitcher and ViewFlipper inherit the ViewAnimator class but the difference is that the former has two views while the latter can have any number of views.

Pre-requisites: Eclipse IDE, Android SDK

Step 1: Create Android project

Launch Eclipse IDE and create a new Android application project called AndroidViewSwitcherDemo with package name com.example.

Step 2: Create layout for ViewSwitcher

Next, create a new XML file under the res/layout folder named activity_switcher and add the following code. This will represent the layout for the ViewSwitcher.

activity_switcher.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="@string/app_name"
        android:textStyle="bold" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/prev"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/previous" />

        <Button
            android:id="@+id/next"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/next" />
        
    </LinearLayout>

    <ViewSwitcher
        android:id="@+id/viewswitcher"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:src="@drawable/ic_launcher" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center_horizontal"
                android:text="@string/text" />
    
        </LinearLayout>
    </ViewSwitcher>

</LinearLayout>

Step 3: Add code to Activity class

Finally, add the following code to your Activity class.

MainActivity.java

package com.example;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import android.app.Activity;

public class MainActivity extends Activity {

	Button buttonPrevious, buttonNext;
	ViewSwitcher viewSwitcher;

	Animation slide_in_left, slide_out_right;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		buttonPrevious = (Button) findViewById(R.id.prev);
		buttonNext = (Button) findViewById(R.id.next);
		viewSwitcher = (ViewSwitcher) findViewById(R.id.viewswitcher);

		slide_in_left = AnimationUtils.loadAnimation(this,
				android.R.anim.slide_in_left);
		slide_out_right = AnimationUtils.loadAnimation(this,
				android.R.anim.slide_out_right);

		viewSwitcher.setInAnimation(slide_in_left);
		viewSwitcher.setOutAnimation(slide_out_right);

		buttonPrevious.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				
				Toast.makeText(getApplicationContext(), "Showing previous view..", Toast.LENGTH_SHORT).show();
				viewSwitcher.showPrevious();
			}
		});

		buttonNext.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				
				Toast.makeText(getApplicationContext(), "Showing next view..", Toast.LENGTH_SHORT).show();
				viewSwitcher.showNext();
			}
		});
	}
}

Save all changes and run the application on an emulator or Android device. If no errors occur then you should see the following output!

android_viewswitcher_1

android_viewswitcher_2

Reference: ViewAnimator in Android

Tutorial #77: Getting started with Google Dart!

Dart is an open source web programming language developed by Google. Like any web programming language, Dart too relies mainly on its cross-compilation to JavaScript feature in order to run on current browsers. It is a class based, object oriented language used to create client side web applications. The Dart project was founded by Lars Bak and Kasper Lund. Some of the key features of the Dart programming language include:

1. Classes – Dart’s classes and interfaces give developers what they need to effectively understand how to define APIs, and the constructs allow the encapsulation and reuse of data and methods.

2. Libraries – The libraries used by Dart will not change during run-time. Pieces of Dart code that are independently developed are thus able to rely upon those shared libraries.

In this tutorial, we will learn how to get started with Dart on Windows!

Pre-requisites: Windows OS (64 bit)

Step 1: Download Dart editor

Google released Dart Editor, an open-source editor based on Eclipse components for Windows, Mac OSX and Linux-based operating systems. You can download the bundle containing both the Dart SDK and the editor from over here.

Step 2: Write a Hello World program

Once you have downloaded Dart editor, launch it and create a New Application called HelloWorld as follows!

dart_1

First, you need to modify the HelloWorld.html file to include a button above the already existing script tags.

<button id="myButton">Click Me!</button>
<div id="myResult"></div>

Next, open the HellowWorld.dart file and add the following code!

import 'dart:html';

void main() {
  var button = query("#myButton");
  button.onClick.listen(addResult);
}
 
void addResult(Event e) {
  var resultDiv = query("#myResult");
  resultDiv.text = "You clicked the button";
}

Finally, save all changes and run the application. A new instance of the chromium browser should launch displaying the HTML content. Click on the button to view the result!

dart_2

That’s it for this tutorial. Stay tuned for more! 🙂

Source: What Google Dart means for web developers

#Event: Get ready for DroidSync 2014

Hello everyone!

If you are Android developer or someone eager to step into the world of mobile technology then this summer could just be the ideal time to kick-start things. The Androcid team is organising a 1 day conference at Ramada Plaza Juhu, Mumbai, on 5th April, 2014. The event plans to showcase the entire Android ecosystem and promises to be an ideal place for developers, business professionals and start-up owners to come together and share information that could help strengthen the Android community.

If you feel you have an expertise, then here’s your chance to showcase your application or submit a 30 minute talk proposal. Looking forward to meet like-minded people? DroidSync plans to provide the ideal platform for you to interact with industry experts, business and management professionals or just anyone who loves to work with Android.

The registrations have already began. Grab your early bird tickets soon! To register and know more about the event please visit the website. Hope to see you at the conference! 🙂

droidsync_2014

Displaying images using Android GridView

Hello everyone!

A GridView is basically used to display items in a two dimensional pattern. The items could be represented as either text or image or a combination of both. In the case of an image gridview we would need to use the BaseAdapter class that helps create a custom adapter source for holding all the items to be displayed in the grid.

Through this post, we would learn how to create a GridView consisting of sample images in Android.

Pre-requisites: Eclipse IDE, Android SDK

Step 1: Create Activity class

Create a new Activity class called ImageGridView in any of your existing Android projects. Add the following code to the class.

ImageGridView.java

package com.example;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class ImageGridView extends Activity {
	
	GridView gv1;
	GridViewAdapter madapter;
	int arr[] = new int[20];
		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_grid);

		gv1=(GridView)findViewById(R.id.grid_view);
		madapter=new GridViewAdapter();
		gv1.setAdapter(madapter);
	}

	public class GridViewAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return arr.length;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub

			LayoutInflater infla=getLayoutInflater();
			View v=infla.inflate(R.layout.main,null);
			ImageView iv1=(ImageView)v.findViewById(R.id.imageView1);
			
			for(int i=0;i<arr.length;i++) {
				arr[i] = R.drawable.android;
			}
			
			iv1.setBackgroundResource(arr[position]);
			return v;
		}
	}
}

Step 2: Create layout for GridView

In order to display the images in a two dimensional grid, we need to create the corresponding layout as follows!

activity_grid.xml

<?xml version="1.0" encoding="utf-8"?>
<GridView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/grid_view"
  android:orientation="vertical"
  android:paddingTop="80px"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:numColumns="4"
  android:columnWidth="60dp"
  android:layout_gravity="center"
  android:horizontalSpacing="5dp"
  android:stretchMode="columnWidth"/>

main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:adjustViewBounds="true" />

</RelativeLayout>

Finally, save all changes. Run the application on an emulator or Android device and you should see the following output!

image_gridview

Reference: BaseAdapter in Android

Believe it or not!

You might say that you don’t believe in superstitions or ghosts or any of those magical illusions that seem impossible or supernatural. You might feel like laughing when you hear stories of people who came back from the dead. As a matter of fact, seeing is believing and one has to experience moments before he/she can draw a conclusion.

Here are two incidents that have occurred recently in my life that makes me write this piece today. Believe it or not, these events have had an impact in some way or the other and at the same time helped me become a little extra cautious.

#1: The Lemon Crush

Unknowingly, on numerous occasions I have stepped on a lemon and some green chillies tied to a string. Back in the olden days, people believed that lime and chillies lying on the road are used to ward off bad luck. Is that really true? I recently stepped on one and ended up having a sore throat 🙁 . I was fine and healthy until I stepped on that yellow trap. My health started deteriorating soon after. I could sense something bad was going to happen. To be honest this has happened on multiple occasions each resulting in ill-health.

#2: The Bad Eye Contact

This is really strange. I didn’t believe it until I became a victim. One fine day, I was leaving home to go to college and one of my friend’s mother happened to meet me at the gate. She started staring at me and asked me as to why I had lost a lot of weight off late. I laughed off her words and left past her. Moments later, I suffered from a stomach ache that forced me to take leave the following day. How can an eye contact suddenly change the health of an individual? Perhaps, that’s why they call it “Gandi Nazar” in Hindi.

How do you avoid all this? Is there any supernatural force that could help give you strength in such situations. Can this force suppress all evil-doings? Yes, indeed and perhaps my mother was right when she said I should strongly believe in HIM. As they say, “Better late than never”. Today, most of my problems are solved by the Almighty. Some might feel HE doesn’t exist, some feel HE does. From now on, HE will always remain closer to my heart.

superstition

Detect missed call event in Android

Hey everyone!

Not too long ago, I had discussed about call event handling in one of my Android programming tips. I had implemented a receiver named MyCallReceiver that could detect an incoming call thereby monitoring the change in phone state.

Through this post, we will learn how to detect a missed call event in Android. A missed call is basically a telephone call that is deliberately terminated by the caller before being answered by its intended recipient. The TelephonyManager class provides certain constants for detecting various call events.

Pre-requisites: Eclipse IDE, Android SDK

Step 1: Modify existing BroadcastReceiver class

Now, let’s add the missed call event logic to our existing MyCallReceiver class as follows!

MyCallReceiver.java


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.widget.Toast;

public class MyCallReceiver extends BroadcastReceiver {

	static boolean isRinging=false;
	static boolean isReceived=false;
	static String callerPhoneNumber;

	@Override
	public void onReceive(Context mContext, Intent intent){

		// Get current phone state
		String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);

		if(state==null)
			return;

		//phone is ringing
		if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)){           
			isRinging =true;
			//get caller's number
			Bundle bundle = intent.getExtras();
			callerPhoneNumber= bundle.getString("incoming_number");
		}

		//phone is received
		if(state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
			isReceived=true;
		}

		// phone is idle
		if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)){
			// detect missed call
			if(isRinging==true && isReceived==false){
				Toast.makeText(mContext, "Got a missed call from : "+callerPhoneNumber, Toast.LENGTH_LONG).show();
			}
		}
	}
}

Step 2: Add permission in manifest file

Do not forget to add the read phone state permission to your AndroidManifest.xml file as follows!

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    <application
        android:allowBackup="true"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- Register the Broadcast receiver -->
        <receiver
            android:name=".MyCallReceiver"
            android:enabled="true">
            <intent-filter>
                <action android:name="android.intent.action.PHONE_STATE" />
            </intent-filter>
        </receiver>

    </application>

</manifest>

Save all changes. Run the application on an Android device. The next time you get a missed call you should see a message being displayed. Happy coding! 🙂

Reference: Android TelephonyManager

Detect internet connection using Qt 5 framework

Hello friends!

In any software framework it is better to check internet connectivity status before making any HTTP requests to avoid HTTP exceptions. For this purpose, Qt provides developers the QNetworkInterface class. The class basically gives a listing of the host’s IP addresses and network interfaces.

In addition to that, the QNetworkAddressEntry class stores one IP address supported by a network interface, along with its associated netmask and broadcast address. It is important to note that only the IPv4 addresses are guaranteed to be listed by this class in all operating system platforms.

Through this post, we will learn how to write a simple Qt program to detect internet connection.

Pre-requisites: Qt Creator, MinGW compiler (Windows – 64 bit)

Launch Qt Creator application and create a new Qt console application project called TestInternetConnection. Choose the default Desktop kit.

Add the following code in the main.cpp file!

main.cpp

#include <QCoreApplication>
#include <QtNetwork/QNetworkInterface>

bool isConnectedToNetwork(){

    QList<QNetworkInterface> ifaces = QNetworkInterface::allInterfaces();
    bool result = false;

    for (int i = 0; i < ifaces.count(); i++) {

        QNetworkInterface iface = ifaces.at(i);
        if ( iface.flags().testFlag(QNetworkInterface::IsUp)
             && !iface.flags().testFlag(QNetworkInterface::IsLoopBack)) {

#ifdef DEBUG
            // details of connection
            qDebug() << "name:" << iface.name() << endl
                     << "ip addresses:" << endl
                     << "mac:" << iface.hardwareAddress() << endl;
#endif


            for (int j=0; j<iface.addressEntries().count(); j++) {
#ifdef DEBUG
                qDebug() << iface.addressEntries().at(j).ip().toString()
                         << " / " << iface.addressEntries().at(j).netmask().toString() << endl;
#endif

                // got an interface which is up, and has an ip address
                if (result == false)
                    result = true;
            }
        }

    }

    return result;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QTextStream output(stdout);

    output << endl << "Connection Status: " << ((isConnectedToNetwork())?"Connected":"Disconnected") << endl;

    return a.exec();
}

.pro file

QT       += core

QT       -= gui
QT       += network
QT       += webkit webkitwidgets
TARGET = TestInternetConnection
CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app
SOURCES += main.cpp

The allinterfaces() method returns a listing of all the network interfaces found on the host machine where as the InterfaceFlag specifies the flags associated with this network interface. Some of the possible values are,

1. QNetworkInterface::IsUp

It’s value is 0x1. It indicates whether the network interface is active.

2. QNetworkInterface::IsLoopBack

It’s value is 0x8. It indicates whether the network interface is a loopback interface, that is, it’s a virtual interface whose destination is the host computer itself.

Save all changes. Build and run the application. If no errors occur then you should see the following output!

output

Tutorial #76: Implement AES-256 encryption/decryption using Java

The Advanced Encryption Standard (AES) is an encryption algorithm designed for securing electronic data established by the U.S National Institute of Standards and Technology (NIST) in 2001. AES is based on Rijndael cipher developed by cryptographers Joan Daemen and Vincent Rijmen. AES carries out its operation on a 4×4 column major order matrix of bytes. The key size used for an AES cipher specifies the number of repetitions of transformation rounds that convert the input, called the plaintext, into the final output, called the ciphertext.

AES is currently available in three key sizes: 128, 192 and 256 bits.The design and strength of all key lengths of the AES algorithm are sufficient to protect classified information up to the SECRET level. As far as security is concerned, AES is considered to be more secure than its predecessor DES. For more information please refer this link.

In this tutorial, we will learn how to implement AES-256 encryption using Java. We will use the Java Cryptography Extension for encryption, decryption, key generation etc. Before proceeding make sure you have downloaded the jurisdiction policy for your respective Java platform from over here. Place the policy files in the {JDK_HOME}\jre\lib\security folder.

Pre-requisites: Eclipse IDE, JDK 1.6 or above

Step 1: Create Java project

Open Eclipse IDE and create a new Java console application project called TestAESExample.

Step 2: Create Java class

Create a new Java class called AESDemo with package name com.example and add the following code!

AESDemo.java

import java.security.AlgorithmParameters;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class AESDemo {

	private static final String password = "test";
	private static String salt;
	private static int pswdIterations = 65536  ;
	private static int keySize = 256;
	private byte[] ivBytes;

	public String encrypt(String plainText) throws Exception {   
		
		//get salt
		salt = generateSalt();		
		byte[] saltBytes = salt.getBytes("UTF-8");
		
		// Derive the key
		SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
		PBEKeySpec spec = new PBEKeySpec(
				password.toCharArray(), 
				saltBytes, 
				pswdIterations, 
				keySize
				);

		SecretKey secretKey = factory.generateSecret(spec);
		SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

		//encrypt the message
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, secret);
		AlgorithmParameters params = cipher.getParameters();
		ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
		byte[] encryptedTextBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
		return new Base64().encodeAsString(encryptedTextBytes);
	}

	@SuppressWarnings("static-access")
	public String decrypt(String encryptedText) throws Exception {

		byte[] saltBytes = salt.getBytes("UTF-8");
		byte[] encryptedTextBytes = new Base64().decodeBase64(encryptedText);

		// Derive the key
		SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
		PBEKeySpec spec = new PBEKeySpec(
				password.toCharArray(), 
				saltBytes, 
				pswdIterations, 
				keySize
				);

		SecretKey secretKey = factory.generateSecret(spec);
		SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

		// Decrypt the message
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes));
	

		byte[] decryptedTextBytes = null;
		try {
			decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}

		return new String(decryptedTextBytes);
	}

	public String generateSalt() {
		SecureRandom random = new SecureRandom();
		byte bytes[] = new byte[20];
		random.nextBytes(bytes);
		String s = new String(bytes);
		return s;
	}
}

Note: In the above example, salt is generated randomly by the generateSalt() method. To implement Base64 encoding and decoding, you need to download the commons-codec library from over here.

Finally, lets add our main class Test.java as follows!

Test.java

package com.example;

public class Test {
	
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub

		AESDemo d = new AESDemo();
			
		System.out.println("Encrypted string:" + d.encrypt("Hello"));			
		String encryptedText = d.encrypt("Hello");
		System.out.println("Decrypted string:" + d.decrypt(encryptedText));			

	}
}

Save all changes. Make sure no errors are present. Run the application. Depending upon the plainText provided you will get the encrypted data.

output

Reference: Performance of encryption algorithms

Save application settings using Qt 5 framework

Hey everyone!

In one of my previous posts, we had seen how to connect to a MySQL database using Qt 5. In that case, we used database tables to store the information. However, Qt also provides the QSettings class allowing developers to save and restore application settings in a portable manner.

As mentioned in the official documentation, QSettings’s API is based on QVariant, allowing you to save most value-based types, such as QString, QRect, and QImage, with the minimum of effort. QSettings objects can be created either on the stack or on the heap (i.e. using new). Constructing and destroying a QSettings object is very fast.

Through this post, we will understand how to save our application settings using the QSettings class.

Pre-requisites: Qt Creator, MinGW compiler ( Windows – 64 bit)

Step 1: Launch Qt Creator and create a new Qt console application project called QtSettingsExample. Choose the default Desktop kit.

Step 2: Add Qt code

Let’s add the code to the main.cpp file as follows!

main.cpp

#include <QCoreApplication>
#include <QSettings>
#include <QDebug>
#include <QString>
#include <QStringList>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QSettings mysettings("CompanyXYZ","ProductABC");

    //set the settings
    mysettings.setValue("Address","Mahape");

    //set the settings with same key
    mysettings.setValue("Address","Vashi");

    //sync the settings
    mysettings.sync();

    //get the settings
    QString str1 = mysettings.value("Address").toString();

    //settings in user scope
    QSettings tempsettings(QSettings::IniFormat, QSettings::UserScope,
                          "MySoft", "Star Runner");

    QSettings inisettings("F:/programs/myapp.ini",
                       QSettings::IniFormat);

    inisettings.beginGroup("TAG1");
    QStringList content = inisettings.allKeys();

    foreach (const QString &childKey, content)
        qDebug() << "Value:" << inisettings.value(childKey).toString();

    inisettings.endGroup();

    qDebug() << "My office location is:" <<str1;
    qDebug() << "My ini file keys:" <<content;

    return a.exec();
}

.pro file

QT       += core

QT       -= gui

TARGET = QtSettingsExample
CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app

SOURCES += main.cpp

Note: QSettings stores settings. Each setting consists of a QString that specifies the setting’s name (the key) and a QVariant that stores the data associated with the key. To write a setting, we use the setValue() method.

Save all changes. Build and run the application. If no errors occur then you should see the following output!

output

Hope this Qt tip was useful! Stay tuned for more! 🙂

Tutorial #75: Connect to MySQL database using Qt 5 framework

Hi everyone!

Just as any other cross platform framework Qt helps to access a database, create and open one or more database connections. Qt supports a list of databases thereby providing access to the API exposed by the underlying DBMS (Database Management System). Once connected, developers can query the database using the QSqlQuery class. It can be used to execute DML (data manipulation language) statements such as SELECT, INSERT etc as well as DDL (data definition language) statements such as CREATE TABLE.

In this tutorial, we will learn how to connect to a MySQL database using the Qt 5 framework. We will also write a simple query to obtain data from our existing table.

Pre-requisites: Qt Creator, MySQL database server, MinGW compiler (Win-x64)

Step 1: Create Qt project

Launch Qt creator and create a new console application project called TestMySQLExample. Choose the default Desktop kit.

Step 2: Add Qt code

Next, you need to make changes to your main.cpp file by adding the following code. Make sure the MySQL database on your machine is up and running.

main.cpp

#include <QCoreApplication>
#include <QApplication>
#include <QtSql/QSql>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlDriver>
#include <QtSql/QSqlQuery>
#include <QDebug>

bool createConnection();

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    if (!createConnection()){

        qDebug() << "Not connected!";
        return 1;
    }
    else{

        qDebug() << "Connected!";

        QSqlQuery query;
        query.exec("SELECT name FROM student");

        while (query.next()) {
            QString name = query.value(0).toString();
            qDebug() << "name:" << name;
        }

        return 0;
    }

    return app.exec();
}

bool createConnection(){
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("localhost");
    db.setDatabaseName("testdb");
    db.setUserName("root");
    db.setPassword("rootpassword");
    if (!db.open()) {
        qDebug() << "Database error occurred";
        return false;
    }
    return true;
}

Important: Before you compile and run the above file, you need to ensure that the libmysql.dll is present within the MySQL directory. Also check whether the path to the same has been added to your Environment Variables.

.pro file

QT       += core
QT       -= gui
QT       += webkit webkitwidgets
QT       += sql
TARGET = TestMySqlExample
CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app

SOURCES += main.cpp

Save all changes. Build and run the application. If no errors occur then you should see the data from your table being displayed in the console. 🙂

output

Reference: Connecting to databases in Qt