Monday, 13 October 2014

Data Adapters in android

No comments :
Adapters are like magician. In android if you want to display block of data in List view or Grid view or any other android widget you have to implement some kind of adapter class in your application. It can be Base adapter or Array adapter or any. So in this class you perform some ugly or magical work. Like creating view for each row of list or grid and then assign data and even you can write some business logic also in that adapter class.

Types of adapters in android are as follows
  1. Base Adapter
  2. Simple Adapter 
  3. Array Adapter
  4. Simple Cursor Adapter
  5. List Adapter
  6. Cursor Adapter
  7. Resource Cursor Adapter
  8. Spinner Adapter
  9. Simple Cursor Tree Adapter
  10. Cursor Tree Adapter
  11. Header View List Adapter
  12. Wrapper List Adapter

Well some of them are totally new for me and i hope for you also. Because they are less known and less used by developers. They consist lots of complexity but for different uses it may help you. just check it out in android documentation. These are the list of adapters till android v 4.4 Kitkat. it may happen android team will add new adapters in next version of android named as android L or in future . So from above all the adapters which are mostly used in android and easy to implement. 

Base Adapter
As name suggest it is base class for all adapter class and interface. Base adapter is abstract class. Base Adapter is a very generic adapter that allows you to do pretty much whatever you want. However, you have to do a bit more coding yourself to get it working. using this class you can define custom view for each row and also you can perform task on object click event also. getView method is basically implemented in this class and you can override it and define your layout in this method. using this class you can bind data with list view and spinner. this is the most used adapter class for binding data in any view. even you can write business logic also in this class. in base adapter class you have to implement even getcount method because on the basis of that adapter will call getview method. Read more

Simple Adapter
when you want to bind static data set to list view you can use simple adapter. you can define xml layout for each row and data can be in array list or in map. each row represent single record of array list. simple adapter class extends Base Adapter class so you have all those methods so you can override even in simple adapter class. data binding is done using view Binder method. Read more

Array Adapter
Second is Array Adapter. Array Adapter is a class which can work with array of data. you need to override only getview method. you can override getview method with different types of parameter. but the main use of array adapter when you want to display a single text view in each row of list. then it is batter to use this adapter. you have to pass data layout or resource file id and text view id in getview method. you can even use image view and other object but for that Base adapter class is perfect. Read more


Simple Cursor Adapter
If your application requires data from local database then you can use simple cursor adapter class to bind data. this is class like simple adapter if you require to display data from database in listview then it is best practice to extend this class. it also works as simple adapter class. different between both is in simple adapter data is in array list and static and in this class data is in cursor and comes from database. data binding in this also done using view Binder method. Read more

Cursor Adapter
if you want to implement this class make sure your table consist one column named as "_id". because cursor traverse data using this column in cursor adapter. and if you want to perform some filtration or swipe cursor then only use this class. it is quite complex so if you are new in android don't try this try some other adapters. one more thing in cursor adapter you have to implement or override new view and bind view method. in which you can define view for each row and bind data also. cursor view already implement getview method so it is better to not to override this method. Read more

Simple Cursor Tree Adapter
last but not list simple cursor tree adapter is useful when you have nested view like nested list view or grid view.  the class provide you method to define layout for child view or group view so if you have data from database and even it is complex (two / three table data) then you can use this adapter class to display data in nested view. Read more

Well there are other adapters also in the list but they are less used and i just covered few details of each adapter class you can find more details about it. click on read more and it will redirect you to documentation where you can find more about it. one more thing, in android View Holder pattern is most famous and use full pattern of saving row layout before it get recycled by garbage collector. so before implementing look after this pattern.

I hope these details help you to understand about adapters. and if it is helpful to you please share this article with your friends. and if you have any thing to say about this article write down in below comment box. new things and suggestion always welcome.

Keep coding...

Read More

Sunday, 17 August 2014

Create or Copy Database in Android

1 comment :
Yesterday i spent whole day behind using my database i mean database is created i just require to use it in app. And i came across many problems, Some of them were really annoying and confusing. For some of them you can find online solution but some are really unknown like null pointer exception or getWritableDatabase method called recursively etc. Even if there is table and also data in it.  some times it also happens you can not copy big database and it is also big problem in android. For that you have to dig up in to your code. You have to debug your app and in android studio it is also tedious task.  so to save your time and without doing all this you can copy database from assets folder to internal storage. Just go through the full tutorial and i hope it will solve all problems regarding coping database.

Steps 
1.  Put below code in your SQLiteOpenHelper Class file. you have to put this code in onCreate method. if you have done some other task in oncreate method then rearrange it after this code. this code will check if database exist then do nothing because if you won't check it will overwrite your database every time you call   getWritableDatabase Or getReadableDatabase Method. beacuse it call onCreate method internally.

2. From your Main Activity only first time call Oncreate method of  SQLiteOpenHelper Class. so for the first time it will create or copy your database. if your database is big you can display progress bar for loading process.


Coping Database Code
package com.androprogrammer.dbdemo;

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;

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


public class DbHelper extends SQLiteOpenHelper 
{
 public static final String DB_NAME = "mydb.db";
 public static final int version = 1;
 public static final String product_table = "tblproduct";
 public static final String order_id = "_id";
 public static final String pname = "pname";
 public static final String desc = "desc";
 public static final String quantity = "quantity";
 public static final String rating = "rating";
 
 private SQLiteDatabase ourdb;
 public Context cont;

 public DbHelper(Context context)
 {
  // TODO Auto-generated constructor stub
  super(context, DB_NAME, null, version);
  this.cont = context;
 }

 @Override
 public void onCreate(SQLiteDatabase db)
    {
        try
        {
            File dbFile = cont.getDatabasePath(DB_NAME);

            if (dbFile.exists())
            {
                //Toast.makeText(cont, "Database Already Exist..." , Toast.LENGTH_LONG).show();
            }
            else
            {
                this.getReadableDatabase();

                InputStream input = cont.getAssets().open(DB_NAME);
                int size = input.available();
                input.close();

                if (size > 0)
                {

                    Log.d("file" , dbFile.getPath());

                    copyDataBase(dbFile);
                    //this.close();
                }
                else
                {
                    // TODO Auto-generated method stub
                    db.execSQL("create table " + product_table +" ( "+ order_id + " INTEGER PRIMARY KEY AUTOINCREMENT , " + pname + " TEXT NOT NULL ," + desc + " TEXT ,"
                            + rating + " INTEGER ," + quantity +" INTEGER );");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        this.ourdb = db;

 }

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

    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     *
     * @param dbFile*/
    private void copyDataBase(File dbFile) throws IOException {

        //Open your local db as the input stream
        InputStream myInput = cont.getAssets().open(DB_NAME);

        //Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(dbFile);

        //transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer))>0)
        {
            myOutput.write(buffer, 0, length);
            Log.d("buf", "" + length);
        }

        //Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();

    }
  
 public DbHelper open() throws SQLException
 {
        if (this.ourdb == null)
        {
           this.ourdb = this.getWritableDatabase();
        }

  return this;
 }

 public synchronized void close()
 {
        if(this.ourdb.isOpen())
      this.ourdb.close();
 }

 public long insert(String name, String des, Float ratings, int quan) throws SQLException
 {
  // TODO Auto-generated method stub
  ContentValues cv = new ContentValues();
  cv.put(pname, name);
  cv.put(desc, des);
  cv.put(rating, ratings);
  cv.put(quantity, quan);
  return this.ourdb.insertOrThrow(product_table, null, cv);

 }

 public Cursor getAllData() throws SQLException
 {
  // TODO Auto-generated method stub
  String [] colums = new String[]{order_id ,pname ,desc ,rating ,quantity};
  Cursor c = this.ourdb.query(product_table,colums, null, null, null, null, null, null);
  return c;
 }

}


As you can see i have even checked if there is no file in assets folder it will create blank database so application won't crash. because it create bad impect when you publish your app in Google play store and it crash so for safety side you can do this. then you can update it later on. now from your main activity just call the onCreate method for that put below code in it.

SQLiteDatabase db = null;
DbHelper helper = new DbHelper(Main.this);
helper.onCreate(db);

Now your database file created or copied so just check it if you have created display method or activity then open it and check it. you can see in debug window also because i have used Logger to know weather database is copied or not so check debug window in editor. now from all other class or activity just call open method. for that put below code in it.

DbHelper helper = new DbHelper(this);
helper.open();

The open method will return instance of database after checking weather it is opened or not. ok now run your app and see the result. if you find any error or if you have any query let me know. Comment in below comment box. it may happen you may find some new error then also let me know so other can also solve that and i will try my best to solve that problem. i have also written tutorial about add, update and display records from database so if you have any query regarding that also check this out.

Keep coding ...  
Read More

Friday, 27 June 2014

Implement Voice input mechanism in android

No comments :
Google Now made us lazy. it can make call for you , can set alarm or reminder for you and much more things that you and i even don't know. And it is without using key board or even without touching your smart phone. as it provide voice input, it is one of the best functionality smart phone provides. Apps and User preference changes day by day and still you provide input using key board i think you have to rethink before next update.  Voice input is supported form android  v 2.3 Ginger bread so you can implement it in your application without using any third party Api. you can implement it using RecognizerIntent.ACTION_RECOGNIZE_SPEECH intent. In this tutorial i am going to show you how you can implement it in your app. just go through full tutorial i am sure you will implement it successfully.

Step -1 : Create New Android application and give name MainActivity to main activity and same name for layout file.
minSdkVersion="11” and targetSdkVersion="17".

you can use below android version also for compilation and build option (As per requirement). now put below code in your project main.xml file. you can set layout as you want but for practice purpose you can go with same.

Main.xml


    

        
            
        

        
        
    


I have given style to the Edit text so it looks nice. below xml file is style applied on it . so now create one resource file and put this code in it.
edittextstyle.xml

    
    
    


Step -2 : Layout is set for your activity. now put below code inside your main class file or where you want voice input. the RecognizerIntent Class allows you to use inbuilt speech recolonization functionality. As i have used this class (intent) it will allow to prompt a dialog box where you can display message what ever you want. 
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak the word");
After user input you can get the result using onActivityResult() method. i get that response and set it into the edit text. now put the below code in class file.
Main.java
package com.androprogrammer.tutorialsamples;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class Main extends Activity {

    EditText word;
    ImageButton bt_voiceinput;
    private static final int REQUEST_CODE = 1234;

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

        // Disable button if no recognition service is present
        PackageManager pm = getPackageManager();
        List<resolveinfo> activities = pm.queryIntentActivities(
                new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
        if (activities.size() == 0) {
            bt_voiceinput.setEnabled(false);
        }

        bt_voiceinput.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startVoiceRecognitionActivity();
            }
        });
        word.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable s) {
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                bt_voiceinput.setEnabled(false);
            }
        });
    }

    private void setRef() {
        // TO set Reference to the xml button object.
        bt_voiceinput = (ImageButton) findViewById(R.id.ib_speak);
        word = (EditText) findViewById(R.id.et_word);
    }

    /**
     * Fire an intent to start the voice recognition activity.
     */
    private void startVoiceRecognitionActivity() {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak the word");
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //If Voice recognition is successful then it returns RESULT_OK
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            if (resultCode == RESULT_OK) {
                ArrayList<string> textMatchList = data
                        .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

                if (!textMatchList.isEmpty()) {
                        String Query = textMatchList.get(0);
                        word.setText(searchQuery);
                }
                //Result code for various error.
            } else if (resultCode == RecognizerIntent.RESULT_NETWORK_ERROR) {
                showToastMessage("Network Error");
            } else if (resultCode == RecognizerIntent.RESULT_NO_MATCH) {
                showToastMessage("No Match");
            } else if (resultCode == RecognizerIntent.RESULT_SERVER_ERROR) {
                showToastMessage("Server Error");
            }
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    private void showToastMessage(String msg) {
        Toast.makeText(Main.this, msg, Toast.LENGTH_LONG).show();
    }
}
       Screen Shots




So that's it from coding side now you can run app and test it. i hope you it will run smoothly.
if you have any query comment it in below comment box.
Keep coding...
Read More

Sunday, 11 May 2014

Implement Push Notification in Your App

No comments :
To alert user about some event or to remind about some event happen in your app ,  push notification is a great and easy way. in android for in app notification you can use alert box but if your application is running in background (background mode) and then to notify user you have to use push notification. on Android devices, when a device receives a push notification, your application's icon and a message appear in the status bar. so in this tutorial i am going to show 2 types of notification. one is just small notification consist of Notification Heading , Sort subject , Icon , time etc. 
and in another type you can display big notification like Gmail notification for new mail (same as image).  it consist Big heading , big message and all other things remain same.

This tutorial will show you how to add push notification functionality in your an Android app to send and receive push notifications.

Step -1 : Create New Android application and give name MainActivity to main activity and same name for layout file. 
minSdkVersion="11”  and 
targetSdkVersion="17".
you can use below android version also for compilation and build option (As per requirment). now put below code in your project main.xml file. you can set layout as you want but for practice purpose you can go with same.
Main.xml


 
 
 
 

 
 
 
 
 

 




In the below class file i have take care of which android version it is so it won't get crashed in older Android version. Below android  3.0 the notification consist simple style of notification  not the bigger one. so we have to take care which version user is using. but firstly you are require to get system service for creating notification. so get it using getSystemService() method of context. 
on small notification button click simple style notification is get created and pending intent will add that intent in intent pool. so system will notify user with NotificationManager.notify() method. 
in other case big notification will be created by second button. in which the big message which will be displayed in notification will be store in Notification.InboxStyle object. that object can store big message , big image (like Screen shot image) etc. 

Step -2 : Hope it will be clear to you. So just now put the below code in Main.java file.
Main.java
package com.androprogrammer.tutorialsamples;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;


public class Main extends Activity {

    Button notification_small , notification_big;
    EditText heading , message;
    String heading_text, subject_text;
    Notification n;
    Notification.Builder nb;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final NotificationManager notificationManager = (NotificationManager)
                getSystemService(NOTIFICATION_SERVICE);
        setRef();

        final Intent intent = new Intent(getApplicationContext(),Main.class);
        final PendingIntent pending = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);

        notification_small.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if(heading.getText().length() < 0)
                {
                    heading_text = "test";
                }
                else
                {
                    heading_text = heading.getText().toString();
                }

                if (Build.VERSION.SDK_INT < 11)
                {
                    n = new Notification(R.drawable.ic_launcher,
                            heading_text,
                            System.currentTimeMillis());

                    n.setLatestEventInfo(
                            getApplicationContext(),
                            heading_text,
                            message.getText().toString(),
                            pending);
                }
                else
                {
                   n = new Notification.Builder(NotificationDemo.this)
                        .setContentTitle(heading_text)
                        .setContentText(message.getText().toString())
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setContentIntent(pending)
                        .setAutoCancel(true)
                        .addAction(R.drawable.abc_ic_clear, "Close", pending).build();
                }
                n.flags |= Notification.FLAG_AUTO_CANCEL;
                notificationManager.notify(0,n);
            }
        });

        notification_big.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                if(heading.getText().length() < 0)
                {
                    heading_text = "test";
                }
                else
                {
                    heading_text = heading.getText().toString();
                }

                if (Build.VERSION.SDK_INT < 11)
                {
                    n = new Notification(R.drawable.ic_launcher,
                            heading_text,
                            System.currentTimeMillis());

                    n.setLatestEventInfo(
                            getApplicationContext(),
                            heading_text,
                            message.getText().toString(),
                            pending);
                }
                else
                {
                   nb = new Notification.Builder(Main.this);

                    Notification.InboxStyle nc =
                            new Notification.InboxStyle();

                    nc.setBigContentTitle(heading_text);

                    String [] text = new String[5];

                    for (int i = 0 ; i < 5 ; i++)
                    {
                        text[i]  = i + ". say hello...";
                        nc.addLine(text[i]);
                    }

                    nb.setStyle(nc);
                }

                notificationManager.notify(100,nb.build());
            }
        });
    }

    private void setRef()
    {
        // TO set Reference to the xml button & edit text object.
        notification_small = (Button) findViewById(R.id.nd_smallnotification);
        notification_big = (Button) findViewById(R.id.nd_bignotification);
        heading = (EditText) findViewById(R.id.nd_etHeading);
        message = (EditText) findViewById(R.id.nd_notificationbody);
    }

}


Step -3 :  Now run your app and write some text for heading and body part of notification. as you can see in below screen shot i have shown both notification type in it. 

if its still not clear to you or have some query ask me in below comment box.if you like it share this tutorial with your friends.

Keep coding...
Screen Shot


Read More

Sunday, 23 March 2014

How To Create Application Folder in SD Card ?

1 comment :
Android framework create your application folder in internal space when you install any of app. it is located at data/data/package-name folder. if you have rooted emulator or smart phone you can check it out. but it has one disadvantage once user remove your app this folder will also be removed but if you want to store data after it also so you can use it if user again install your app or you want to store some info related to your app on SD card then you can create it using this tutorial.  just follow the steps of this tutorial.

Step -1 : Create New Android application and give name MainActivity to main activity and same name for layout file. minSdkVersion="11” and targetSdkVersion="17".you can use below android version also for compilation and build option. put this below code in your mainactivity so once user start your app it will be created so you can use it further in your app.
MainActivity.java
package com.androprogrammer.tutorialsamples;

import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.widget.Toast;

import java.io.File;


public class MainActivity extends ActionBarActivity {

    String folderPath;
    File folder;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sdcard_folder_demo);
        folderPath = createFolder();
    }

    private String createFolder()
    {
            String extStorageDirectory = Environment
                    .getExternalStorageDirectory().toString();
            folder = new File(extStorageDirectory, "/Android/data/" + getPackageName());
            if(!folder.exists())
            {
                folder.mkdir();
                Toast.makeText(MainActivity.this, "Folder Created At :" + folder.getPath().toString(), Toast.LENGTH_LONG).show();
            }
            else
            {
                Toast.makeText(MainActivity.this, "Folder Already At :" + folder.getPath().toString(), Toast.LENGTH_LONG).show();
            }
            return folder.getPath().toString();
    }
}
Step -2 : i have created createFolder() method it will also check if folder is already created or not. if it is there it return path to the folder. the above code will create folder with your package name so to check out run your application. one more thing in order to create or write in SD card you required to add below permission in manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Screen Shots
androprogrammer.comandroprogrammer.com

That's it check out your application folder in SD card at Android/data/package-name folder. now you can store any data in or file in this folder using string returned by that method.

Keep coding.. 
Read More