Wednesday 14 August 2013

Registration Activity Using Shared Preference Android

3 comments
Android comes with plenty of options to store persistent Application data. The approach you use depends upon your needs, is your data is private or how much space you need and is it accessible to other application or not.
In Android we have following option for storing persistence data.
Shared Preference -> store data in key- value pairs.
Internal Storage  -> Private data on device.
External storage -> public data on sharable storage.
SQLite Database -> more structure approach to store data in tables.

Today i am going to discuss about shared Preference:-
So Shared Preference is a framework that store persistent data in key-value pairs. You can store any primitive data type with Shared Preference.
To get a shared Preference object, use one of the following.
getSharedPreferences() -> if you have multiple sharedpreferecne file
getPreferences() -> if you need only on preference file for your activity
you Also need one editor to write into the file

Initialization:-
SharedPreferences pref=getApplicationContext().getSharedPreferences("MyFilename", 0);
// 0 - for private mode
Editor editor = pref.edit(); // Getting editor to edit the data

Storing Data:-
Editor.editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "arpit"); // Storing string
editor.putInt("key_name", "10"); // Storing integer
editor.putFloat("key_name", "10.5"); // Storing float
editor.putLong("key_name", "10.5L"); // Storing long

Need to commit in order to put value in file
editor.commit();
// commit changes

Retrieve data:-
// returns stored preference value
// If value is not present return second param value - In this case null
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean

Clearing data:-
editor.remove("key_name"); // will delete key name

To delete all value of Shared Preference file call
clear();


Now we begin with our project.
In this project i will make an activity where user registered with the details like Name, Email and Password. Only After completing each of the details user is allowed to be in next activity where he/she will see the entered information.
Use of Shared Preference in the project:-
The information entered is stored in shared preference.
Value of the second activity is generated after fetching of information from the same file.


Step 1:- Make a new project named, SharedPreferenceSample.
Step 2:- As there will be two activity in the project, lets first define the xml for both.
activity_main.xml
<RelativeLayout 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:gravity="fill_horizontal"
    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:id="@+id/textview_Register"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="80dp"
        android:text="Registeration"
        android:textAppearance="?android:attr/textAppearanceLarge" />
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textview_Register"
        android:layout_marginTop="25dp"
        android:text="Enter Name"
        android:textAppearance="?android:attr/textAppearanceMedium" />
    <EditText
        android:id="@+id/editText_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:ems="10" >
   
    </EditText>
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText_name"
        android:layout_below="@+id/editText_name"
        android:layout_marginTop="19dp"
        android:text="E-mail:"
        android:textAppearance="?android:attr/textAppearanceMedium" />
    <EditText
        android:id="@+id/editText_mail"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="20dp"
        android:ems="10" >
    </EditText>
    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText_mail"
        android:layout_below="@+id/editText_mail"
        android:layout_marginTop="31dp"
        android:text="Password:"
        android:textAppearance="?android:attr/textAppearanceMedium" />
    <EditText
        android:id="@+id/editText_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView3"
        android:layout_below="@+id/textView3"
        android:layout_marginTop="24dp"
        android:ems="10" >
    </EditText>
    <Button
        android:id="@+id/button_register"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText_password"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:text="Register" />
</RelativeLayout>

second.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp" >
    <TextView
        android:id="@+id/second_text_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Username"
        android:textAppearance="?android:attr/textAppearanceMedium" />
    <TextView
        android:id="@+id/second_text_email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Email"
        android:textAppearance="?android:attr/textAppearanceMedium" />
    <TextView
        android:id="@+id/second_text_pass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Password"
        android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>


Step 3:- MainActivity Class
package com.arpit.sharedpreferencesample;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
    SharedPreferences pref;
    Editor editor;
    Button btn_register;
    EditText et_name, et_pass, et_email;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    et_name = (EditText) findViewById(R.id.editText_name);
    et_pass = (EditText) findViewById(R.id.editText_password);
    et_email = (EditText) findViewById(R.id.editText_mail);
    btn_register = (Button) findViewById(R.id.button_register);
   
    // creating an shared Preference file for the information to be stored
    // first argument is the name of file and second is the mode, 0 is private mode

   
    pref = getSharedPreferences("Registration", 0);
    // get editor to edit in file
    editor = pref.edit();
   
    // the tap of button we will fetch the information from three edittext    btn_register.setOnClickListener(new View.OnClickListener() {
       
        @Override
        public void onClick(View v) {
        String name = et_name.getText().toString();
        String email = et_email.getText().toString();
        String pass = et_pass.getText().toString();
       
        if(et_name.getText().length()<=0){
            Toast.makeText(MainActivity.this, "Enter name", Toast.LENGTH_SHORT).show();
        }
        else if( et_email.getText().length()<=0){
            Toast.makeText(MainActivity.this, "Enter email", Toast.LENGTH_SHORT).show();
        }
        else if( et_pass.getText().length()<=0){
            Toast.makeText(MainActivity.this, "Enter password", Toast.LENGTH_SHORT).show();
        }
        else{
       
        // as now we have information in string. Lets stored them with the help of editor
        editor.putString("Name", name);
        editor.putString("Email",email);
        editor.putString("Password",pass);
        editor.commit();   // commit the values
        
        // after saving the value open next activity
        Intent ob = new Intent(MainActivity.this, Second.class);
        startActivity(ob);
       
        }   
        }
    });
   }
}

Step 4:- Second class file
package com.arpit.sharedpreferencesample;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;
// in this activity we will fetch the value entered in main activity
public class Second extends Activity{
    TextView tv_name, tv_pass, tv_email;
    SharedPreferences pref;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);
    tv_name = (TextView) findViewById(R.id.second_text_name);
    tv_email = (TextView) findViewById(R.id.second_text_email);
    tv_pass = (TextView) findViewById(R.id.second_text_pass);
    pref = getSharedPreferences("Registration", 0);
   // retrieving value from Registration
    String name = pref.getString("Name", null);
    String email = pref.getString("Email", null);
    String password = pref.getString("Password", null);
   
    // Now set these value into textview of second activity   
    tv_name.setText(name);
    tv_pass.setText(password);
    tv_email.setText(email);
     }
}


Step 5:- Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.arpit.sharedpreferencesample"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.arpit.sharedpreferencesample.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>
        <activity android:name=".Second"></activity>
   
    </application>
</manifest>


Result:-
Entered information                                Fetched value on second activity
firstsecond
Catch Me On: CreateAppFaster.com
Read More...

Saturday 10 August 2013

Android Admob Sample Code

1 comment
Today we have an interesting topic to cover that will help many android developer who have their free android application on Google Play. The Google Admob Ads SDK is the latest generation in Google mobile advertising having well refined ads for mobile.
Lets begin with sample code demo:-
Step 1:- Get Registered with Admob to get the publisher Id
After filling basic information Click –> Add Site/App
and fill the information Like below.
registration



Step 2:- Download the SDK
download sdk


Step 3:- Get the Publisher ID, hover over added site/App and click on Manage setting where you Get the publisher ID.
publisherId


Step 4:- Create a sample demo project named, AdmobSample.Add GoogleAdMobAdsSdk.jar file into libs folder of project directory.


Step 5:- Android Manifest
Add an activity and permission into manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.arpit.admobsample"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.arpit.admobsample.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>
        <activity
            android:name="com.google.ads.AdActivity"
          android:configChanges="keyboard
|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />
    </application>
</manifest>


Step 6:- Let me tell you one more thing
 you can add Ads in your application in two ways :-
1.In Xml
2.In Java file
Either Define Ads  in xml or in Java.



Let us get started with the xml method.
The highlighted code is a way to add Ads in your Xml. There is no need to do anything in java file now.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <com.google.ads.AdView
        android:id="@+id/ad"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        ads:adSize="BANNER"
        ads:adUnitId="YOUR_PUBLISHER_ID"
        ads:loadAdOnCreate="true" />   //load code while onCreate calls

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
</LinearLayout>

Second way is to define Ads in java source file
package com.arpit.admobsample;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
public class MainActivity extends Activity {
    LinearLayout layout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
// this is code to add Ads in javafile. Took a layout and define add in it.
    layout = (LinearLayout) findViewById(R.id.linear);
  AdView ad = new AdView(MainActivity.this, AdSize.BANNER, "YOUR_PUBLISHER_ID");
        layout.addView(ad);
        ad.loadAd(new AdRequest());
    }
   
}



Result:- Google Play Ad
result
Catch Me On: CreateAppFaster.com
Read More...

Thursday 8 August 2013

Mobile Development–Native v/s PhoneGap?

1 comment


I have been  asked many a times which is the best solution of developing mobile application. Since I have experience of both Application development methods. Today I will try to provide a little insight of how these two methods actually works.
Native
Every mobile system runs into its own Operating System like Apple has ios  in iphone’s , Blackberry has its own OS whereas Android OS runs on many mobile devices. Therefore in Native Development we have to use particular language like objective C for ios development and java for android development which in-turn have there libraries which provides us the access to the various device functionality like Contacts, read sms etc.

PhoneGap
“PhoneGap is a free and open source framework that allows you to create mobile apps using standardized web APIs for the platforms you care about.”phonegap.com

PhoneGap uses the existing skills of programming like HTML, CSS, JavaScript for the development of the Mobile Application. It Provides own environment for application, and have its own jar and JavaScript files. phonegap or cordova js have access to all mobile device functionality like camera, sms, Bluetooth via the phonegap plugins.
Verdict
  • I think it is very important to understand the need and functionality of your application.
  • Development in phonegap results in multiplatform application whereas in native it is only build for supported OS.
  • Application Performance Is much better in native compared to phonegap.
  • In my opinion phonegap should be used where application have to rendered more content similar to html pages in web rather than having more device related functionality.
  • Native development should be used where application frequently access device related functionality and where performance is an issue.

Catch Me On: CreateAppFaster.com
Read More...

Wednesday 7 August 2013

Android SQLite Database Demo

1 comment


Today we will discussed about SQLite Database in android.
android.database Package have all necessary classes for working with database. android.database.sqlite Package contains the SQLite related classes.
To extends the functionality of SQLite in your application we have to extends SQLiteOpenHelper.
This class have two methods
onCreate() – will create database for the first time.
onUpdate() – will be used to update the existing database.


Lets Begins.
Step 1:-
<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:padding="5dp"
   
  >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name"
        android:textAppearance="?android:attr/textAppearanceMedium" />
    <EditText
        android:id="@+id/editText_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:ems="10" >
       
    </EditText>
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Marks"
        android:layout_marginTop="10dp"
        android:textAppearance="?android:attr/textAppearanceMedium" />
    <EditText
        android:id="@+id/editText_marks"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:layout_marginTop="10dp"
        android:inputType="phone" >
   
    </EditText>
    <Button
        android:id="@+id/buttonAddDetail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Add Details" />
</LinearLayout>
Step 2:- create database via DatabaseManager Class
package com.arpit.sqlitedemo;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseManager extends SQLiteOpenHelper {
    private Context context;
    private static String DB_NAME = "SampleDatabase";
    private static int DB_VERSION = 1;
    public static final String TABLE_STUDENT = "Student";
   

    public DatabaseManager(Context context) {
        // TODO Auto-generated constructor stub
        super(context, DB_NAME, null, DB_VERSION);
        this.context = context;
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL("CREATE TABLE Student(    Id INTEGER NOT NULL PRIMARY KEY, Name TEXT NOT NULL, Marks TEXT NOT NULL)");
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE " + TABLE_STUDENT + "IF EXISTS");
        this.onCreate(db);
    }
}
Step 3:- Create MainActivity Class
package com.arpit.sqlitedemo;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
    EditText etName, etMarks;
    Button btn_add;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        etName = (EditText) findViewById(R.id.editText_name);
        etMarks = (EditText) findViewById(R.id.editText_marks);
        btn_add = (Button) findViewById(R.id.buttonAddDetail);
        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isInserted = false;
                String name = etName.getText().toString();
                String marks = etMarks.getText().toString();
                if (etName.getText().length() <= 0) {
                    Toast.makeText(MainActivity.this, "Please Enter name",
                            Toast.LENGTH_SHORT).show();
                } else if (etMarks.getText().length() <= 0) {
                    Toast.makeText(MainActivity.this, "Please Enter Marks",
                            Toast.LENGTH_SHORT).show();
                } else {
                    DatabaseController controller = new DatabaseController(
                            MainActivity.this);
                    isInserted = controller.addValuesIntoTable(name, marks);
                    if (isInserted) {
                        Toast.makeText(getBaseContext(),
                                "Successfuly Inserted", Toast.LENGTH_SHORT)
                                .show();
                    }
//                    etName.setText("");
//                    etMarks.setText("");
                }
            }
        });
    }
}
Step 4:- Create a controller class ie DatabaseController.java which will put the information in the database via the help of ContentValues.

package com.arpit.sqlitedemo;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
public class DatabaseController {
    private Context context;
    public DatabaseController(Context context) {
        // TODO Auto-generated constructor stub
        this.context = context;
    }
    public boolean addValuesIntoTable(String name, String marks) {
   
        boolean inserted=false;
        ContentValues values=new ContentValues();
        values.put("Name", name);
        values.put("Marks", marks);
        try
        {           
        SQLiteDatabase sqlDb=new DatabaseManager(context).getWritableDatabase();
       
        if(sqlDb.isOpen())
        {
            long inserted_row=sqlDb.insert(DatabaseManager.TABLE_STUDENT, null, values);
            if(inserted_row>0)
            {
                inserted=true;
            }
        }
       
        sqlDb.close();
        }
        catch(Exception exception)
        {
            exception.printStackTrace();
        }
       
        // TODO Auto-generated method stub
        return inserted;
       
    }
   
}



Screenshot_2013-08-07-15-59-19Screenshot_2013-08-07-16-00-09Screenshot_2013-08-07-16-24-19

Catch Me On: CreateAppFaster.com
Read More...

Tuesday 6 August 2013

PhoneGap Application – “Words of Wisdom”

1 comment
 
banner_512 

"Words Of Wisdom" is a motivational and inspirational application covering each and every aspect of an individual’s life that requires continuous source of motivation and correct guidance in order to live a happy and a meaningful life. Inspiration comes in many forms to people. Some individuals respond to books, while other might respond to stories, movies, reflections or autobiographies from various well-known leaders and scholars.
As we are living in a techno world with smart-phones in hand; WOW serves a great need for a larger audience in order to bring a source of motivation on the fingertips. Covering the major concerns of each person’s life, it will allow users to use it anytime, anywhere and keep themselves motivated thereby winning in every phase of their lives. WOW can be seen as a "Happiness Manufacturing Application.

Technical aspect of this application, that this application is an attempt to explore and understand the Phone Gap Framework. In Order to make this application, we got to know various thing about Phone Gap application building process.

This application is made by my colleague and me, you can download this application at Google Store.


Read More...

Sunday 4 August 2013

Delete Row Item in ListView Android

2 comments
Today I will display how to delete row item from List in android. In this project I will be having list, on long press of item  an alert dialog box will pop out asking you for confirmation with having Yes and Cancel Button.




Step 1:- create activity_main.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" >
    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>
</LinearLayout>



Step 2:- create list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dip"
    android:textSize="16dip"
    android:textStyle="bold" >
</TextView>

Step 3:- MainActivity.java
package com.arpit.deleterowlistview;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
    ListView lv;
    ArrayAdapter<String> adapter;
    List<String> arr;
    String[] language = { "C", "Java", "C++", "C-sharp", ".Net", "SQL",
            "Android", "PhoneGap", "Ios", "windows", "PHP", "Phyton", "Perl" };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv = (ListView) findViewById(R.id.listView1);
        arr = new ArrayList<String>(Arrays.asList(language));
        adapter = new ArrayAdapter<String>(this, R.layout.list_row, arr);
        lv.setAdapter(adapter);
       
        lv.setOnItemLongClickListener(new OnItemLongClickListener() {
            // setting onItemLongClickListener and passing the position to the function
                      @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                    int position, long arg3) {
                removeItemFromList(position);  
               
                return true;
            }
        });
    }
// method to remove list item
    protected void removeItemFromList(int position) {
        final int deletePosition = position;
       
        AlertDialog.Builder alert = new AlertDialog.Builder(
                MainActivity.this);
   
        alert.setTitle("Delete");
        alert.setMessage("Do you want delete this item?");
        alert.setPositiveButton("YES", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TOD O Auto-generated method stub
                   
                    // main code on after clicking yes
                    arr.remove(deletePosition);
                    adapter.notifyDataSetChanged();
                    adapter.notifyDataSetInvalidated();
     
            }
        });
        alert.setNegativeButton("CANCEL", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        });
     
        alert.show();
     
    }
}


Catch Me On: CreateAppFaster.com
Read More...

Saturday 3 August 2013

Search Bar in ListView Android

1 comment
We have made list many a time’s in android, in this tutorial I will be adding search bar functionality to the ListView. In this project I have added a search bar above the list. ListView will be filtered on the basis of text added on the search bar. It is useful where you have a  long list.


Step 1:- create activity_main.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">
   <EditText
       android:id="@+id/search_editText"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:hint="Search"/>
  
    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
       >
    </ListView>
</LinearLayout>

Step 2:- create list_row.xml for particular row
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dip"
    android:textSize="16dip"
    android:textStyle="bold" >
</TextView>

Step 3:- MainActivity.java
package com.arpit.searchbarandroidlistview;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity {
    ListView lv;
    EditText etsearch;
    ArrayAdapter<String> adapter;
    List<String> arr;
    String[] language = { "C", "Java", "C++", "C-sharp", ".Net", "SQL",
            "Android", "PhoneGap", "Ios", "windows", "PHP", "Phyton", "Perl" };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv = (ListView) findViewById(R.id.listView1);
        etsearch = (EditText) findViewById(R.id.search_editText);
        arr = new ArrayList<String>(Arrays.asList(language));
        adapter = new ArrayAdapter<String>(this, R.layout.list_row, arr);
        lv.setAdapter(adapter);
       
      // code for searching from list
 
etsearch.addTextChangedListener(new TextWatcher() {
           
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
                 MainActivity.this.adapter.getFilter().filter(s);
               
            }
           
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
                // TODO Auto-generated method stub
               
            }
           
            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
               
            }
        });       
           }
}



Catch Me On: CreateAppFaster.com
Read More...

Android Slide Animation Effect Between Page Transition

Leave a Comment
Today I am going to make a demo project on slide animation effect between page transition
Step 1 :- Create anim folder under res folder
Step 2:- In anim folder create two xml file,
  • anim_in.xml
<?xml version="1.0" encoding="utf-8"?>
    <set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
    android:fromXDelta="-100%"
    android:toXDelta="0"
    android:duration="1250" />
</set>
  • anim_out.xml
<?xml version="1.0" encoding="utf-8"?>
   <set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
    android:fromXDelta="0"
    android:toXDelta="100%"
    android:duration="1250" />
  </set>
Step 3:- Create two xml file under layout folder
  • first.xml
<RelativeLayout 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"
>
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Next" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:textSize="25sp"
        android:layout_marginTop="42dp"
        android:text="@string/hello_world" />
</RelativeLayout>
  • second.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Second Activity"
        android:textSize="25sp" />
</LinearLayout>
Step 4:- Create MainActivity.java file
package com.arpit.activitypagetransition;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
    Button btnNext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

     overridePendingTransition(R.anim.anim_in, R.anim.anim_out);
        setContentView(R.layout.first);
        System.out.println("----main activity---onCreate---");
        btnNext = (Button) findViewById(R.id.button1);
        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent ob = new Intent(MainActivity.this, Second.class);
                startActivity(ob);
            }
        });
    }
    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        System.out.println("----main activity---onStart---");
    overridePendingTransition(R.anim.anim_in, R.anim.anim_out);    
  }
}
Step 5:- create Second.java file
package com.arpit.activitypagetransition;
import android.app.Activity;
import android.os.Bundle;
public class Second extends Activity {
    protected void onCreate(Bundle savedInstance){
        super.onCreate(savedInstance);
overridePendingTransition(R.anim.anim_in, R.anim.anim_out);
        setContentView(R.layout.second);
        System.out.println("----Secondactivity activity---onCreates---");
    }
   
}
Step 6:- AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.arpit.activitypagetransition"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.arpit.activitypagetransition.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>
        <activity
            android:name=".Second"></activity>
    </application>
</manifest>

Follow Fade-in and Fade-out effect



Catch Me On: CreateAppFaster.com
Read More...

Android Fade in and Fade out Animation Effect between page Transition

Leave a Comment
Android Comes with pretty cool animation, today I am going to discuss how to do fade in and fade out transition between the pages.
Step 1 :- Create anim folder under res folder
Step 2:- In anim folder create two xml file,
  • fadein.xml
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
   android:interpolator="@android:anim/accelerate_interpolator"
   android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="2000" />
  • fadeout.xml
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
   android:interpolator="@android:anim/accelerate_interpolator"
   android:fromAlpha="1.0" android:toAlpha="0.0" android:
duration="2000" />
Step 3:- Create two xml file under layout folder
  • first.xml
<RelativeLayout 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"
>
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Next" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:textSize="25sp"
        android:layout_marginTop="42dp"
        android:text="@string/hello_world" />
</RelativeLayout>
  • second.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Second Activity"
        android:textSize="25sp" />
</LinearLayout>
Step 4:- Create MainActivity.java file
package com.arpit.activitypagetransition;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
    Button btnNext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        overridePendingTransition(R.anim.fadein, R.anim.fadeout);
        setContentView(R.layout.first);
        System.out.println("----main activity---onCreate---");
        btnNext = (Button) findViewById(R.id.button1);
        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent ob = new Intent(MainActivity.this, Second.class);
                startActivity(ob);
            }
        });
    }
    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        System.out.println("----main activity---onStart---");
        overridePendingTransition(R.anim.fadein, R.anim.fadeout);
       }
}
Step 5:- create Second.java file
package com.arpit.activitypagetransition;
import android.app.Activity;
import android.os.Bundle;
public class Second extends Activity {
    protected void onCreate(Bundle savedInstance){
        super.onCreate(savedInstance);
        overridePendingTransition(R.anim.fadein, R.anim.fadeout);
        setContentView(R.layout.second);
        System.out.println("----Secondactivity activity---onCreates---");
    }
   
}
Step 6:- AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.arpit.activitypagetransition"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.arpit.activitypagetransition.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>
        <activity
            android:name=".Second"></activity>
    </application>
</manifest>


Catch Me On: CreateAppFaster.com
Read More...

Friday 2 August 2013

Image ListView in Android

1 comment
Today I will discussed how to make Image ListView in android. I have made a demo project named ImageListView.
Step 1:- create activity_main.xml,  in this xml I have defined how image and text will come with respective to each other.
Step 2:- the image used in the project is in the drawable folder. Please put image in your drawable folder before you are going to refer them.
Step 3:- This is how my main.java looks

package com.example.imagelistview;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
public class Main extends ListActivity implements OnItemClickListener {
    String []proList ={"Android", "C", "C++", "Java", "JavaScript", "Jquery", "Objective C", "iOS"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // setting up an adapter and passing an array and context of this class        setListAdapter(new MyListAdapter(this,proList));
       
        ListView listView = getListView();
        listView.setOnItemClickListener(this);
       
    }
    @Override
    public void onItemClick(AdapterView<?> adapter, View arg1, int position, long arg3) {
         
        String str = adapter.getItemAtPosition(position).toString();
        Toast.makeText(getBaseContext(), "You Clicked on: "+str, Toast.LENGTH_SHORT).show();
       
    }
}   

Step 4:- Setting up an Adapter named MyListAdapter.java
package com.example.imagelistview;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MyListAdapter extends ArrayAdapter<String>{
   
    private String []values;
    private Context context;
   
    public MyListAdapter(Context context, String []values) {
        // TODO Auto-generated constructor stub
        super(context,R.layout.activity_main,values);
        this.context = context;
        this.values = values;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
       
        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       
        View rowView = inflater.inflate(R.layout.activity_main, parent,false);
       
        TextView textV = (TextView)rowView.findViewById(R.id.textView1);
        ImageView imgV = (ImageView)rowView.findViewById(R.id.imageView1);
       
        textV.setText(values[position]);
       
        String str =values[position];
       
            if(str.equalsIgnoreCase("android")){
                imgV.setImageResource(R.drawable.ic_launcher);
            }else
                if(str.equalsIgnoreCase("c")){
                    imgV.setImageResource(R.drawable.c);
                }else
                    if(str.equalsIgnoreCase("c++")){
                        imgV.setImageResource(R.drawable.cplus);
                    }else
                        if(str.equalsIgnoreCase("Java")){
                            imgV.setImageResource(R.drawable.java);
                        }else
                            if(str.equalsIgnoreCase("javascript")){
                                imgV.setImageResource(R.drawable.javascript);
                            }else
                                if(str.equalsIgnoreCase("jquery")){
                                    imgV.setImageResource(R.drawable.jquery);
                                }else
                                    if(str.equalsIgnoreCase("objective c")){
                                        imgV.setImageResource(R.drawable.objectivec);
                                    }else
                                        if(str.equalsIgnoreCase("ios")){
                                            imgV.setImageResource(R.drawable.ios);
                                        }
               
       
        return rowView;
    }
}
Read More...