Monday, November 18, 2013

Google Analytics Event Tracking on button click from Android Application

Integrate Google Analytics Event Tracking on button click from Android Application

Hi folks this post about how to track from our android application button click event or How many time opend our application we can track..etc..

First you need to create Goolge analytics account and then create one application get track app id.
Below see how to create Googel analytics account.
Google Analytics site
Step 1
After create account . Create new application get track id
Step 2

Select Mobile app tab.Check the screen below


Step 3 ;
Get tracking ID



Now come to Android.How to Configure google analytics into our android application.
Download latest Google Analytics Jar  and put this jar into your lib folder


Step 1

Goto res/values folder ->Create file name called  analytics.xml . Then paste this code into that file.

Paste this code into analytics.xml file. and add your track id here
<?xml version="1.0" encoding="utf-8" ?>



<resources>

  <!--Replace placeholder ID with your tracking ID-->

  <string name="ga_trackingId">UA-XXXX-Y</string>



  <!--Enable automatic activity tracking-->

  <bool name="ga_autoActivityTracking">true</bool>



  <!--Enable automatic exception tracking-->

  <bool name="ga_reportUncaughtExceptions">true</bool>

</resources>


Step 2

Add following permission into your android manifest file.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


Step 3
Then come to activity . Add click event in btn click and track page event add in onStart() and onStop method.
MainActivity .class
<?xml version="1.0" encoding="utf-8" ?>

package com.example.googleanalyticssample;
 
 
import com.google.analytics.tracking.android.EasyTracker;
 
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
 
public class MainActivity extends Activity {
 
                    Button btnClick;
                    @Override
                    protected void onCreate(Bundle savedInstanceState) {
                                         super.onCreate(savedInstanceState);
                                         setContentView(R.layout.activity_main);
                                         btnClick = (Button)findViewById(R.id.button1);
                                         btnClick.setOnClickListener(new OnClickListener() {
                                                             
                                                             @Override
                                                             public void onClick(View v) {
                                                             
                                                                                 Utils.pushbtnClickedEvent(MainActivity.this, "Button Clicked");
                                                             }
                                         });
                    }
 
                    @Override
                    public boolean onCreateOptionsMenu(Menu menu) {
                                         // Inflate the menu; this adds items to the action bar if it is present.
                                         getMenuInflater().inflate(R.menu.main, menu);
                                         return true;
                    }
 
                    
                    
                    @Override
                       protected void onStart() {
                          super.onStart();
                          EasyTracker.getInstance(this).activityStart(this); 
                          Utils.pushOpenScreenEvent(this, "Main Activity Opened");
                         
                       }
                    @Override
                    protected void onStop() {
                                         // TODO Auto-generated method stub
                                           
                                         super.onStop();
                                          Utils.pushCloseScreenEvent(this, "Main Activity Closed");
                                          EasyTracker.getInstance(this).activityStop(this); // Add this method
                                         
                                         
                                         
                                           
                    }
 
}



  

Utils.class
this class contain track btn event and page event method.
package com.example.googleanalyticssample;
import android.content.Context;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.Fields;
import com.google.analytics.tracking.android.MapBuilder;
import com.google.analytics.tracking.android.Tracker;
import com.google.tagmanager.DataLayer;
import com.google.tagmanager.TagManager;
public class Utils {
                   
                      /**
                       * Push an "openScreen" event with the given screen name. Tags that match that event will fire.
                       */
                     private static Tracker tracker;
                      public static void pushOpenScreenEvent(Context context, String screenName) {
                                          
                          // Instantiate the Tracker
                                           tracker =  EasyTracker.getInstance(context);
                                           tracker.set(Fields.SCREEN_NAME, screenName);
                                         // Send a screenview.
                                           tracker.send(MapBuilder
                                             .createAppView()
                                             .build()
                                           );
                      }
                     
                      /**
                       * Push an "Button clicked" event with the given screen name. Tags that match that event will fire.
                       */
                      public static void pushbtnClickedEvent(Context context, String clickE) {
                                           tracker =  EasyTracker.getInstance(context);
                                         // Values set directly on a tracker apply to all subsequent hits.
                                           tracker.set(Fields.SCREEN_NAME, "Home Screen");

                                           // This screenview hit will include the screen name "Home Screen".
                                           tracker.send(MapBuilder.createAppView().build());

                                           // And so will this event hit.
                                           tracker.send(MapBuilder
                                             .createEvent("UI", "click", "my btn clicked", null)
                                             .build()
                                           );
                      }
                      /**
                       * Push a "closeScreen" event with the given screen name. Tags that match that event will fire.
                       */
                      public static void pushCloseScreenEvent(Context context, String screenName) {
                                        
                          // Instantiate the Tracker
                                           tracker =  EasyTracker.getInstance(context);
                                           tracker.set(Fields.SCREEN_NAME, screenName);
                                         // Send a screenview.
                                           tracker.send(MapBuilder
                                             .createAppView()
                                             .build()
                                           );
                      }
}



Click the button then u can able to see in analytics page how many time you clicked button.

Analytics page report

In report you can able to see event name and whcih categry and action. then screen name


Screen view report


*********************
if you have more doubt see official document  HERE.

Monday, November 11, 2013

Copy SQLite database file from Assets folder in android

Copy SQLite database file from Assets folder in android

This post about how to copy SQLite database file to asset folder android.

WHY?
Some time we will get manual entry SQLite DB. So that file directly we can’t use it.

Manul entry DB file screen shot



Put sqllite db file into asset folder


Source Code

SqlLiteDbHelper.class

/**
 * Copyright 2013-present http://iamvijayakumar.blogspot.com/.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.

 */

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class SqlLiteDbHelper extends SQLiteOpenHelper {

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_PATH = "/data/data/com.copy.copydatabasefromasset/databases/";
    // Database Name
    private static final String DATABASE_NAME = "mycontacts";
 // Contacts table name
    private static final String TABLE_CONTACT = "contact";
 private SQLiteDatabase db;
    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_EMAILID = "emailid";
    private static final String KEY_MOBILENO = "mobileno";
   
    Context ctx;
    public SqlLiteDbHelper(Context context) {
       super(context, DATABASE_NAME, null, DATABASE_VERSION);
       ctx = context;
    }
  
   
    // Getting single contact
    public Contact Get_ContactDetails(String name) {
       SQLiteDatabase db = this.getReadableDatabase();

       Cursor cursor = db.query(TABLE_CONTACT, new String[] { KEY_ID,
                     KEY_NAME, KEY_EMAILID, KEY_MOBILENO }, KEY_NAME + "=?",
              new String[] { name }, null, null, null, null);
if (cursor != null && cursor.moveToFirst()){
              Contact cont = new Contact(cursor.getString(1), cursor.getString(2), cursor.getString(3));
              // return contact
              cursor.close();
              db.close();

              return cont;
             
       }
              return null;
    }
    public void CopyDataBaseFromAsset() throws IOException{
       InputStream in  = ctx.getAssets().open("mycontacts");
       Log.e("sample", "Starting copying" );
       String outputFileName = DATABASE_PATH+DATABASE_NAME;
       File databaseFile = new File( "/data/data/com.copy.copydatabasefromasset/databases");
        // check if databases folder exists, if not create one and its subfolders
        if (!databaseFile.exists()){
            databaseFile.mkdir();
        }
      
       OutputStream out = new FileOutputStream(outputFileName);
      
       byte[] buffer = new byte[1024];
       int length;
      
      
       while ((length = in.read(buffer))>0){
              out.write(buffer,0,length);
       }
       Log.e("sample", "Completed" );
       out.flush();
       out.close();
       in.close();
      
    }
   
   
    public void openDataBase () throws SQLException{
       String path = DATABASE_PATH+DATABASE_NAME;
       db = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.CREATE_IF_NECESSARY);
    }

       @Override
       public void onCreate(SQLiteDatabase db) {
             
             
       }

       @Override
       public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
              // TODO Auto-generated method stub
             
       }
}


Contact.class

package com.copy.copydatabasefromasset;

/**
 * Copyright 2013-present http://iamvijayakumar.blogspot.com/.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Contact {
      
       public String name = "";
       public String email = "";
       public String mobileNo = "";
       public String getName() {
              return name;
       }
       public void setName(String name) {
              this.name = name;
       }
       public String getEmail() {
              return email;
       }
       public void setEmail(String email) {
              this.email = email;
       }
       public String getMobileNo() {
              return mobileNo;
       }
       public void setMobileNo(String mobileNo) {
              this.mobileNo = mobileNo;
       }
        // constructor
       public Contact (String name,String email,String mobileNo){
              this.email = email;
              this.mobileNo = mobileNo;
              this.name = name;
       }
      

       public Contact (){
             
       }
}
 Screen Shot 
Retrive data from Sqlite DB

MainActivity.class
package com.copy.copydatabasefromasset;
/**
 * Copyright 2013-present http://iamvijayakumar.blogspot.com/.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.IOException;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {
    TextView contact ;
    SqlLiteDbHelper dbHelper = new SqlLiteDbHelper(this);;
    Contact contacts ;
       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              contact = (TextView)findViewById(R.id.contact);
              dbHelper = new SqlLiteDbHelper(this);
              try {
                     dbHelper.CopyDataBaseFromAsset();
              } catch (IOException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              }
              dbHelper.openDataBase();
              contacts = new Contact();
              contacts = dbHelper.Get_ContactDetails("vijay");
        contact.setText(contacts.name +"\n" +contacts.email +"\n" +contacts.mobileNo);
             
       }

      
}






Check out this may be help you

Related Posts Plugin for WordPress, Blogger...