Saturday, 23 January 2016

SQLite example for CRUD operation in Android


DatabaseConnectionAPI.java

import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseConnectionAPI extends SQLiteOpenHelper {

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "contactsManager";

// Contact table name
private static final String TABLE_CONTACTS = "contacts";

// Contact Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";

public DatabaseConnectionAPI(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

// Create tables again
onCreate(db);
}

/**
* All CRUD(Create, Read, Update, Delete) Operations
*/

// Adding new contact
public int addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone

// Inserting Row
int i= (int) db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
return i;
}

// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();

Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();

Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}

// Getting All Contact
public ArrayList<Contact> getAllContacts() {
ArrayList<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;

SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);

// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}

// return contact list
return contactList;
}

// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());

// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}

// Deleting single contact
public void deleteContact(String id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { id });
db.close();
}


// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();

// return count
return cursor.getCount();
}

}

layout_add.xml

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


    <android.support.design.widget.TextInputLayout
        android:id="@+id/input_layout_email"
        android:layout_width="match_parent"
         android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/margin_10dp">

        <EditText
            android:id="@+id/edt_email"
            style="@style/Edittext"
            android:hint="Name" />

    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/input_layout_pass"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/input_layout_email">

        <EditText
            android:id="@+id/edt_password"
            style="@style/Edittext"
            android:hint="Phone"
            android:maxLength="10"
            android:inputType="phone" />

    </android.support.design.widget.TextInputLayout>

    <TextView
        android:id="@+id/txt_login"
        style="@style/LargeTextView"
        android:layout_below="@+id/input_layout_pass"
        android:layout_centerHorizontal="true"

        android:layout_marginTop="@dimen/margin_20dp"
         android:padding="@dimen/margin_10dp"
        android:text="ADD CONTACT"
        android:textColor="@color/colorPrimary" />


</RelativeLayout>

layout_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">


    <TextView
        android:id="@+id/txt_no_data"
        style="@style/LargeTextView"
        android:text="There are no any data added yet."
        android:layout_centerHorizontal="true"
        android:layout_margin="@dimen/margin_10dp"/>
    <RelativeLayout
        android:id="@+id/rel_tops"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">


        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
             android:cacheColorHint="@android:color/transparent"
            android:divider="@android:color/transparent"
            android:visibility="visible"
            />


    </RelativeLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_input_add" />

</RelativeLayout>

row_list_layout.xml

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


    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_gravity="center"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        card_view:cardCornerRadius="2dp"
        card_view:contentPadding="10dp">
    <RelativeLayout
        android:id="@+id/rel_top"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp">

        <TextView
            android:id="@+id/row_txt_name"
            style="@style/LargeTextView"
            android:text="Name"/>


        <TextView
            android:id="@+id/row_txt_ph"
            style="@style/NormalTextView"
            android:layout_below="@+id/row_txt_name"
            android:text="Name"/>


    </RelativeLayout>
    </android.support.v7.widget.CardView>
</RelativeLayout>

AddContact.java

package com.example.sphere65.sqlitedemoexample;

 import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;



public class AddContact extends AppCompatActivity {

    TextInputLayout mTextInputLayoutEmail;
    EditText mEditTextEmail;

    TextInputLayout mTextInputLayoutPassword;
    EditText mEditTextPassword;

     TextView mTextViewLogin;
        DatabaseConnectionAPI mDatabaseConnectionAPI;
      @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_add);
          mDatabaseConnectionAPI=new DatabaseConnectionAPI(this);

        mTextInputLayoutEmail=(TextInputLayout)findViewById(R.id.input_layout_email);
        mTextInputLayoutPassword=(TextInputLayout)findViewById(R.id.input_layout_pass);
        mEditTextEmail=(EditText)findViewById(R.id.edt_email);
        mEditTextPassword=(EditText)findViewById(R.id.edt_password);

        mTextViewLogin=(TextView)findViewById(R.id.txt_login);

        mEditTextEmail.addTextChangedListener(new MyTextWatcher(mEditTextEmail));
        mEditTextPassword.addTextChangedListener(new MyTextWatcher(mEditTextPassword));
        mTextViewLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginDone();

            }
        });



    }



    private void loginDone() {


        if (!validateEmail()) {
            return;
        }

       else if (!validatePassword()) {
            return;
        }
        else
        {



           int i= mDatabaseConnectionAPI.addContact(new Contact(mEditTextEmail.getText().toString(), mEditTextPassword.getText().toString()));
            if (i>0)
            {
                Toast.makeText(getApplicationContext(), "Data inserted successfully.", Toast.LENGTH_SHORT).show();
                clearAllField();
                finish();
            }
         

        }

    }


    public void clearAllField()
    {

        mEditTextEmail.clearFocus();
        mEditTextPassword.clearFocus();
     }
    private boolean validateEmail() {
        String email = mEditTextEmail.getText().toString().trim();

        if (email.isEmpty()  ) {
            mTextInputLayoutEmail.setError("Enter name");
            requestFocus(mEditTextEmail);
            return false;
        } else {
            mTextInputLayoutEmail.setErrorEnabled(false);
        }

        return true;
    }

    private boolean validatePassword() {
        if (mEditTextPassword.getText().toString().trim().isEmpty()) {
            mTextInputLayoutPassword.setError("Enter Phone");
            requestFocus(mEditTextPassword);
            return false;
        } else {
            mTextInputLayoutPassword.setErrorEnabled(false);
        }

        return true;
    }


    private void requestFocus(View view) {
        if (view.requestFocus()) {
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
    }
    private class MyTextWatcher implements TextWatcher {

        private View view;

        private MyTextWatcher(View view) {
            this.view = view;
        }

        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        public void afterTextChanged(Editable editable) {
            switch (view.getId()) {

                case R.id.edt_email:
                    validateEmail();
                    break;
                case R.id.edt_password:
                    validatePassword();
                    break;
            }
        }
    }
}

EditContact.java

package com.example.sphere65.sqlitedemoexample;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class EditContact extends AppCompatActivity {

    TextInputLayout mTextInputLayoutEmail;
    EditText mEditTextEmail;

    TextInputLayout mTextInputLayoutPassword;
    EditText mEditTextPassword;

    TextView mTextViewLogin;
    DatabaseConnectionAPI mDatabaseConnectionAPI;
    Contact mContact;
    String value = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_add);
        mDatabaseConnectionAPI = new DatabaseConnectionAPI(this);

        Bundle extras = getIntent().getExtras();

        if (extras != null) {
            value = extras.getString("id");
        }
        mContact = new Contact();
        mContact = mDatabaseConnectionAPI.getContact(Integer.parseInt(value));


        mTextInputLayoutEmail = (TextInputLayout) findViewById(R.id.input_layout_email);
        mTextInputLayoutPassword = (TextInputLayout) findViewById(R.id.input_layout_pass);
        mEditTextEmail = (EditText) findViewById(R.id.edt_email);
        mEditTextPassword = (EditText) findViewById(R.id.edt_password);

        mTextViewLogin = (TextView) findViewById(R.id.txt_login);

        mEditTextEmail.addTextChangedListener(new MyTextWatcher(mEditTextEmail));
        mEditTextPassword.addTextChangedListener(new MyTextWatcher(mEditTextPassword));
        mTextViewLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginDone();

            }
        });
        mEditTextEmail.setText(mContact.getName());
        mEditTextPassword.setText(mContact.getPhoneNumber());
        mTextViewLogin.setText("EDIT CONTACT");

    }


    private void loginDone() {


        if (!validateEmail()) {
            return;
        } else if (!validatePassword()) {
            return;
        } else {


            int i = mDatabaseConnectionAPI.updateContact(new Contact(mEditTextEmail.getText().toString(), mEditTextPassword.getText().toString(), Integer.parseInt(value)));
            if (i > 0) {
                Toast.makeText(getApplicationContext(), "Data updated successfully.", Toast.LENGTH_SHORT).show();
                clearAllField();
                finish();
            }
             

        }

    }


    public void clearAllField() {

        mEditTextEmail.clearFocus();
        mEditTextPassword.clearFocus();
    }

    private boolean validateEmail() {
        String email = mEditTextEmail.getText().toString().trim();

        if (email.isEmpty()) {
            mTextInputLayoutEmail.setError("Enter name");
            requestFocus(mEditTextEmail);
            return false;
        } else {
            mTextInputLayoutEmail.setErrorEnabled(false);
        }

        return true;
    }

    private boolean validatePassword() {
        if (mEditTextPassword.getText().toString().trim().isEmpty()) {
            mTextInputLayoutPassword.setError("Enter Phone");
            requestFocus(mEditTextPassword);
            return false;
        } else {
            mTextInputLayoutPassword.setErrorEnabled(false);
        }

        return true;
    }


    private void requestFocus(View view) {
        if (view.requestFocus()) {
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
    }

    private class MyTextWatcher implements TextWatcher {

        private View view;

        private MyTextWatcher(View view) {
            this.view = view;
        }

        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        public void afterTextChanged(Editable editable) {
            switch (view.getId()) {

                case R.id.edt_email:
                    validateEmail();
                    break;
                case R.id.edt_password:
                    validatePassword();
                    break;
            }
        }
    }
}


ContactListActivity.java

package com.example.sphere65.sqlitedemoexample;
import java.util.ArrayList;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;


public class ContactListActivity extends Activity {
    /**
     * Called when the activity is first created.
     */
    DatabaseConnectionAPI db;
    ListView mListView;
    CusTomListAdapter mCusTomListAdapter;
    ArrayList<Contact> contacts;
    TextView mTextViewNoData;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main);

          db = new DatabaseConnectionAPI(this);
        mTextViewNoData=(TextView)findViewById(R.id.txt_no_data);
        mListView = (ListView) findViewById(R.id.list);
        /**
         * CRUD Operations
         * */
        // Inserting Contact
        /*Log.d("Insert: ", "Inserting ..");
        db.addContact(new Contact("Harshal", "9100000000"));
        db.addContact(new Contact("Srinivas", "9199999999"));
        db.addContact(new Contact("Tommy", "9522222222"));
        db.addContact(new Contact("Karthik", "9533333333"));*/

        // Reading all contacts
        Log.d("Reading: ", "Reading all contacts..");
          contacts = db.getAllContacts();
        if (contacts.size()>0)
        {
            mCusTomListAdapter=new CusTomListAdapter(AndroidSQLiteTutorialActivity.this,contacts);
            mListView.setAdapter(mCusTomListAdapter);
            mTextViewNoData.setVisibility(View.GONE);
            mListView.setVisibility(View.VISIBLE);
        }
        else
        {
            mTextViewNoData.setVisibility(View.VISIBLE);
            mListView.setVisibility(View.GONE);
        }

        for (Contact cn : contacts) {
            String log = "Id: " + cn.getID() + " ,Name: " + cn.getName() + " ,Phone: " + cn.getPhoneNumber();
            // Writing Contact to log
            Log.d("Name: ", log);

        }
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /*Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();*/
                Intent mIntent=new Intent(AndroidSQLiteTutorialActivity.this,AddContact.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(mIntent);
            }
        });
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view,final int i, long l) {
                CharSequence colors[] = new CharSequence[] {"Edit", "Delete"};

                AlertDialog.Builder builder = new AlertDialog.Builder(AndroidSQLiteTutorialActivity.this);
                builder.setTitle("Choose Action");
                builder.setItems(colors, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            Intent mIntent = new Intent(AndroidSQLiteTutorialActivity.this, EditContact.class);
                            mIntent.putExtra("id", String.valueOf(contacts.get(i).getID()));
                            startActivity(mIntent);
                        } else {
                            db.deleteContact(String.valueOf(contacts.get(i).getID()));
                            contacts = db.getAllContacts();
                            if (contacts.size() > 0) {
                                mCusTomListAdapter = new CusTomListAdapter(AndroidSQLiteTutorialActivity.this, contacts);
                                mListView.setAdapter(mCusTomListAdapter);
                                mTextViewNoData.setVisibility(View.GONE);
                                mListView.setVisibility(View.VISIBLE);
                            } else {
                                mListView.setVisibility(View.GONE);
                                mTextViewNoData.setVisibility(View.VISIBLE);
                            }


                        }

                    }
                });
                builder.show();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        ArrayList<Contact> contacts = db.getAllContacts();
        if (contacts.size()>0)
        {
            mCusTomListAdapter=new CusTomListAdapter(AndroidSQLiteTutorialActivity.this,contacts);
            mListView.setAdapter(mCusTomListAdapter);
            mListView.setVisibility(View.VISIBLE);
            mTextViewNoData.setVisibility(View.GONE);
        }
        else
        {
            mListView.setVisibility(View.GONE);
            mTextViewNoData.setVisibility(View.VISIBLE);
        }

    }

    public class CusTomListAdapter extends BaseAdapter {

        Activity mActivity;
        ArrayList<Contact> list;



        public CusTomListAdapter(AndroidSQLiteTutorialActivity mainActivity, ArrayList<Contact> contacts) {
            list =  contacts;
            mActivity = mainActivity;

        }


        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int i) {
            return i;
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View convertView, ViewGroup viewGroup) {
            LayoutInflater inflator = mActivity.getLayoutInflater();
            convertView = inflator.inflate(R.layout.row_list_layout, null);
            TextView mTextViewName = (TextView) convertView.findViewById(R.id.row_txt_name);
            TextView mTextViewPh = (TextView) convertView.findViewById(R.id.row_txt_ph);

            mTextViewName.setText(list.get(i).getName());
            mTextViewPh.setText(list.get(i).getPhoneNumber());

            return convertView;
        }
    }

}

Friday, 22 January 2016

ViewPager Indicator circular style in Android

pager_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:fitsSystemWindows="true"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:src="@mipmap/abc1"
        android:id="@+id/img_pager_item"
        android:scaleType="fitXY"
        android:adjustViewBounds="true"
        android:clickable="false"/>

</LinearLayout>


activity_viewpager_demo.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:fitsSystemWindows="true"
    tools:context="com.androprogrammer.tutorials.samples.ViewPagerDemo">

    <android.support.v4.view.ViewPager
        android:id="@+id/pager_introduction"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:listitem="@layout/pager_item" />

    <RelativeLayout
        android:id="@+id/viewPagerIndicator"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:layout_alignParentBottom="true"
        android:layout_marginTop="5dp"
        android:gravity="center">

        <LinearLayout
            android:id="@+id/viewPagerCountDots"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_centerHorizontal="true"
            android:gravity="center"
            android:orientation="horizontal" />

        <ImageButton
            android:id="@+id/btn_next"
            android:layout_width="42dip"
            android:layout_height="42dip"
            android:layout_alignParentRight="true"
            android:layout_marginRight="15dip"
            android:background="@drawable/btn_round_semitransperant"
            android:src="@mipmap/ic_navigation_arrow_forward" />

        <ImageButton
            android:id="@+id/btn_finish"
            android:layout_width="42dip"
            android:layout_height="42dip"
            android:layout_alignParentRight="true"
            android:layout_marginRight="15dip"
            android:background="@drawable/btn_round_semitransperant"
            android:contentDescription="Let's start"
            android:src="@mipmap/ic_navigation_check"
            android:visibility="gone" />

    </RelativeLayout>


</RelativeLayout>

ViewPagerDemo.java

package com.example.sphere65.pagerindicatorcircularstyle;

import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;


public class ViewPagerDemo extends AppCompatActivity implements ViewPager.OnPageChangeListener, View.OnClickListener{

    protected View view;
    private ImageButton btnNext, btnFinish;
    private ViewPager intro_images;
    private LinearLayout pager_indicator;
    private int dotsCount;
    private ImageView[] dots;
    private ViewPagerAdapter mAdapter;

    private int[] mImageResources = {
            R.mipmap.abc1,
            R.mipmap.abc2,
            R.mipmap.abc3,
            R.mipmap.abc4,
            R.mipmap.abc5
    };

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_viewpager_demo);
        intro_images = (ViewPager) findViewById(R.id.pager_introduction);
        btnNext = (ImageButton) findViewById(R.id.btn_next);
        //btnSkip = (Button) findViewById(R.id.btn_skip);
        btnFinish = (ImageButton) findViewById(R.id.btn_finish);

        pager_indicator = (LinearLayout) findViewById(R.id.viewPagerCountDots);

        btnNext.setOnClickListener(this);
        //btnSkip.setOnClickListener(this);
        btnFinish.setOnClickListener(this);

        mAdapter = new ViewPagerAdapter(ViewPagerDemo.this, mImageResources);
        intro_images.setAdapter(mAdapter);
        intro_images.setCurrentItem(0);
        intro_images.setOnPageChangeListener(this);
        setUiPageViewController();

       //toolbar.setVisibility(View.GONE);

//        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    }

    /*@Override
    public void setReference() {
      //  view = LayoutInflater.from(this).inflate(R.layout.activity_viewpager_demo,container);


    }*/

    private void setUiPageViewController() {

        dotsCount = mAdapter.getCount();
        dots = new ImageView[dotsCount];

        for (int i = 0; i < dotsCount; i++) {
            dots[i] = new ImageView(this);
            dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            );

            params.setMargins(4, 0, 4, 0);

            pager_indicator.addView(dots[i], params);
        }

        dots[0].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        switch (item.getItemId()) {
            // Respond to the action bar's Up/Home button
            case android.R.id.home:
                finish();
                // NavUtils.navigateUpFromSameTask(this);
                // return true;
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_next:
                intro_images.setCurrentItem((intro_images.getCurrentItem() < dotsCount)
                        ? intro_images.getCurrentItem() + 1 : 0);
                break;

            case R.id.btn_finish:
                finish();
                break;
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        for (int i = 0; i < dotsCount; i++) {
            dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
        }

        dots[position].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));

        if (position + 1 == dotsCount) {
            btnNext.setVisibility(View.GONE);
            btnFinish.setVisibility(View.VISIBLE);
        } else {
            btnNext.setVisibility(View.VISIBLE);
            btnFinish.setVisibility(View.GONE);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}

ViewPagerAdapter.java

package com.example.sphere65.pagerindicatorcircularstyle;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;


/**
 * Created by Wasim on 11-06-2015.
 */
public class ViewPagerAdapter extends PagerAdapter {

    private Context mContext;
    private int[] mResources;

    public ViewPagerAdapter(Context mContext, int[] mResources) {
        this.mContext = mContext;
        this.mResources = mResources;
    }

    @Override
    public int getCount() {
        return mResources.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((LinearLayout) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View itemView = LayoutInflater.from(mContext).inflate(R.layout.pager_item, container, false);

        ImageView imageView = (ImageView) itemView.findViewById(R.id.img_pager_item);
        imageView.setImageResource(mResources[position]);

        container.addView(itemView);

        return itemView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((LinearLayout) object);
    }
}

Login Example with JSON web service Android


For integrating JSON service example you need below jar for that
1. apache-mime4j-0.6.jar
2. gson-2.1.jar
3. httpmime-4.0.1,jar
4. json_simple-1.1.jar

layout_login.xml

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

    <!--<android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        local:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        local:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize" />-->


    <RelativeLayout
        android:id="@+id/rel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true">

        <TextView
            android:id="@+id/txt_title"
            style="@style/LargeTextView"
            android:layout_marginBottom="@dimen/margin_15dp"
            android:layout_centerHorizontal="true"
            android:hint="Sign IN" />
        <android.support.design.widget.TextInputLayout
            android:id="@+id/input_layout_email"
            android:layout_width="match_parent"
            android:layout_below="@+id/txt_title"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/margin_10dp">

            <EditText
                android:id="@+id/edt_email"
                style="@style/Edittext"
                android:hint="Email" />

        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:id="@+id/input_layout_pass"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/input_layout_email">

            <EditText
                android:id="@+id/edt_password"
                style="@style/Edittext"
                android:hint="Password"
                android:inputType="textPassword" />

        </android.support.design.widget.TextInputLayout>

        <TextView
            android:id="@+id/txt_forgot_password"
            style="@style/NormalTextView"
            android:layout_below="@+id/input_layout_pass"
            android:layout_marginLeft="@dimen/margin_10dp"
            android:layout_marginTop="@dimen/margin_10dp"
            android:text="@string/forgot_password" />

        <TextView
            android:id="@+id/txt_new_user"
            style="@style/NormalTextView"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/input_layout_pass"
            android:layout_marginLeft="@dimen/margin_10dp"
            android:layout_marginRight="@dimen/margin_10dp"
            android:layout_marginTop="@dimen/margin_10dp"
            android:text="@string/new_user" />

        <TextView
            android:id="@+id/txt_login"
            style="@style/NormalTextView"
            android:layout_below="@+id/txt_forgot_password"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="@dimen/margin_20dp"
            android:background="@drawable/login_rect"
            android:padding="@dimen/margin_10dp"
            android:text="LOGIN"
            android:textColor="@android:color/white" />

    </RelativeLayout>

</RelativeLayout>

LoginActivity.java

package com.example.sphere65.loginregisterskeleton;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import parser.GetSecrateKey;

public class LoginActivity extends AppCompatActivity {

    TextInputLayout mTextInputLayoutEmail;
    EditText mEditTextEmail;

    TextInputLayout mTextInputLayoutPassword;
    EditText mEditTextPassword;

    TextView mTextViewForgotPassword;
    TextView mTextViewNewUser;
    TextView mTextViewLogin;

    Context context;
    String evalue="";
    GetSecrateKey mGetSecrateKey;
    PostParseGet mPostParseGet;
    AllMethods mAllMethods;
    ProgressDialog mProgressDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_login);
        context=this;
        mGetSecrateKey=new GetSecrateKey();
        mPostParseGet=new PostParseGet(LoginActivity.this);
        mAllMethods=new AllMethods(LoginActivity.this);
        mTextInputLayoutEmail=(TextInputLayout)findViewById(R.id.input_layout_email);
        mTextInputLayoutPassword=(TextInputLayout)findViewById(R.id.input_layout_pass);
        mEditTextEmail=(EditText)findViewById(R.id.edt_email);
        mEditTextPassword=(EditText)findViewById(R.id.edt_password);
        mTextViewForgotPassword=(TextView)findViewById(R.id.txt_forgot_password);
        mTextViewNewUser=(TextView)findViewById(R.id.txt_new_user);
        mTextViewLogin=(TextView)findViewById(R.id.txt_login);

        mEditTextEmail.addTextChangedListener(new MyTextWatcher(mEditTextEmail));
        mEditTextPassword.addTextChangedListener(new MyTextWatcher(mEditTextPassword));
        mTextViewLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginDone();

            }
        });
         

         

    }

    

    private void loginDone() {


        if (!validateEmail()) {
            return;
        }

       else if (!validatePassword()) {
            return;
        }
        else
        {
            Toast.makeText(getApplicationContext(), "You have logged in successfully.", Toast.LENGTH_SHORT).show();

            /* Call Login web service with neccessory parameter
            if (mAllMethods.check_Internet()==true)
            {
                new loginAysnTask().execute();
            }
            else
            {
                mAllMethods.ShowDialog(LoginActivity.this,"",getString(R.string.net_not_available),"OK");
            }
            */
            clearAllField();
        }

    }

    public class loginAysnTask extends AsyncTask<Void,Void,Void>    {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog=ProgressDialog.show(LoginActivity.this,"","Loading..");
        }

        @Override
        protected Void doInBackground(Void... voids) {
            mGetSecrateKey=(GetSecrateKey)mPostParseGet.login(mGetSecrateKey,mEditTextEmail.getText().toString(),mEditTextPassword.getText().toString());
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            if (mProgressDialog!=null)
            {
                mProgressDialog.dismiss();
            }
            if(mPostParseGet.isNetError){
                mAllMethods.ShowDialog(LoginActivity.this, "", getString(R.string.net_not_available), "OK");
            }
            else if (mPostParseGet.isOtherError) {
                mAllMethods.ShowDialog(LoginActivity.this, "", getString(R.string.data_not_found), "OK");
            }
            else
            {
                if (mGetSecrateKey!=null)
                {
                    if (mGetSecrateKey.getRes_code().equalsIgnoreCase("1"))
                    {
                        Toast.makeText(getApplicationContext(), mGetSecrateKey.getRes_msg(), Toast.LENGTH_SHORT).show();
                    }
                    else
                    {
                        Toast.makeText(getApplicationContext(), mGetSecrateKey.getRes_msg(), Toast.LENGTH_SHORT).show();

                    }

                }
            }

        }
    }
    public void clearAllField()
    {

        mEditTextEmail.clearFocus();
        mEditTextPassword.clearFocus();
     }
    private boolean validateEmail() {
        String email = mEditTextEmail.getText().toString().trim();

        if (email.isEmpty() || !isValidEmail(email)) {
            mTextInputLayoutEmail.setError(getString(R.string.err_msg_email));
            requestFocus(mEditTextEmail);
            return false;
        } else {
            mTextInputLayoutEmail.setErrorEnabled(false);
        }

        return true;
    }

    private boolean validatePassword() {
        if (mEditTextPassword.getText().toString().trim().isEmpty()) {
            mTextInputLayoutPassword.setError(getString(R.string.err_msg_password));
            requestFocus(mEditTextPassword);
            return false;
        } else {
            mTextInputLayoutPassword.setErrorEnabled(false);
        }

        return true;
    }

    private static boolean isValidEmail(String email) {
        return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }

    private void requestFocus(View view) {
        if (view.requestFocus()) {
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
    }
    private class MyTextWatcher implements TextWatcher {

        private View view;

        private MyTextWatcher(View view) {
            this.view = view;
        }

        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        public void afterTextChanged(Editable editable) {
            switch (view.getId()) {

                case R.id.edt_email:
                    validateEmail();
                    break;
                case R.id.edt_password:
                    validatePassword();
                    break;
            }
        }
    }
}

AllUrl.java

public class AllUrl {

     public static String url="https://www.mylink.com/webservice/";

}

AllMethods.java

package com.example.sphere65.loginregisterskeleton;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class AllMethods {
ConnectivityManager mConnectivityManager;
NetworkInfo mNetworkInfo;
boolean isNetError;
public Activity mActivity;
Context mContext;
FragmentActivity mActivity2;
Dialog mDialogRentRimDialog;


public     String formatPhoneNumber(String number){
number  =   number.substring(0, number.length()-4) + "-" + number.substring(number.length()-4, number.length());
number  =   number.substring(0,number.length()-8)+")"+number.substring(number.length()-8,number.length());
number  =   number.substring(0, number.length()-12)+"("+number.substring(number.length()-12, number.length());
number  =   number.substring(0, number.length()-14)+"+"+number.substring(number.length()-14, number.length());

return number;
}


 
 
 
public   void hideSoftKeyboard(Activity activity) {
   InputMethodManager inputMethodManager = (InputMethodManager)  activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
   inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
public AllMethods() {
// TODO Auto-generated constructor stub

}
public AllMethods(Context mContext) {
// TODO Auto-generated constructor stub
this.mContext=mContext;

}
public AllMethods(Activity mContext) {
// TODO Auto-generated constructor stub
this.mActivity=mContext;

}
public AllMethods(FragmentActivity mContext) {
// TODO Auto-generated constructor stub
this.mActivity=mContext;


}
 
public void ShowDialog(final Activity activity, String Title ,String Message,String Ok) 
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
alertDialogBuilder.setTitle(Title);
alertDialogBuilder
.setMessage(Message)
.setCancelable(true)
.setPositiveButton(Ok,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
 });
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();

}




public   void hideKeyboard(Activity  mActivity2,View view) {
        InputMethodManager inputMethodManager =(InputMethodManager)mActivity2.getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
public void ShowDialog(FragmentActivity activity, String Title ,String Message,String Ok)
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
alertDialogBuilder.setTitle(Title);
alertDialogBuilder
.setMessage(Message)
.setCancelable(true)
.setPositiveButton(Ok,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
 });
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();

}
/*public   boolean checkEmail(String EdittextString) {
return FragmentDashboard.emailPattern.matcher(EdittextString).matches();
}*/
public boolean check_Internet()
{
mConnectivityManager= (ConnectivityManager)mActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();

if(mNetworkInfo != null && mNetworkInfo.isConnectedOrConnecting())
{
isNetError = false;
return true;
}
else
{
isNetError = true;
return false;
}
}
 
}

PostParseGet.java


package com.example.sphere65.loginregisterskeleton;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.app.FragmentActivity;

import com.google.gson.Gson;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;

import parser.GetSecrateKey;

public class PostParseGet {

public Activity mContext;
public boolean isNetError = false;
public boolean isOtherError = false;
public boolean isDeviceToken = false;
List<NameValuePair> nameValuePairs;
Object mFillObject;

public static ArrayList<String>mflist;
ConnectivityManager mConnectivityManager;
NetworkInfo mNetworkInfo;

Gson mGson;

public PostParseGet(Activity context) {
mContext = context;
mGson = new Gson();
mflist=new ArrayList<String>();
}
public PostParseGet(FragmentActivity context) {
mContext = context;
mGson = new Gson();
mflist=new ArrayList<String>();
}

public Object getmFillObject() {
return mFillObject;
}

public void setmFillObject(Object mFillObject) {
this.mFillObject = mFillObject;
}

public boolean isDeviceToken() {
return isDeviceToken;
}

public void setDeviceToken(boolean isDeviceToken) {
this.isDeviceToken = isDeviceToken;
}

/**
* Function checks internet if avail, Post data to particular Url and filled
* json object relating to the response.
* @param string
* @param nameValuePairs
* @param object
* @param context
* @return object
* @throws CustomException
* */
public Object postHttpURL(String url, List<NameValuePair> nameValuePairs, Object mObject) {
HttpPost httppost;
HttpParams httpParameters;
int timeoutConnection = 60000;
HttpClient httpclient = null;
HttpResponse response = null;
String data = "";
isOtherError = false;

System.out.println("Url " + url);
mFillObject= null;

if(check_Internet())
{
try {
mFillObject = mObject.getClass().newInstance();
HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

DefaultHttpClient client = new DefaultHttpClient();

SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

// Set verifier
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
//  HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
httppost = new HttpPost(url);
httpParameters = new BasicHttpParams();
// HttpConnectionParams.setSoTimeout(httpParameters, timeoutConnection);
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
httpclient = new DefaultHttpClient(httpParameters);


MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
System.out.println("nameValuePairs "+nameValuePairs.size());
if (nameValuePairs != null)
{
for(int index=0; index < nameValuePairs.size(); index++)
{
String paramName=nameValuePairs.get(index).getName();
String paramValue=nameValuePairs.get(index).getValue();
System.out.println("paramName "+paramName);
System.out.println("paramValue "+paramValue);

if(paramName.equalsIgnoreCase("docsimage")||paramName.equalsIgnoreCase("faceimage") )
{
 
if(paramValue.length()>0)
{
   
entity.addPart(paramName, new FileBody(new File (paramValue)));

 

}
else
{
// mflist.clear();
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));

}
}
httppost.setEntity(entity);
}


response = httpclient.execute(httppost);
System.out.println("httppost " + httppost.toString());
data = EntityUtils.toString(response.getEntity());

System.out.println("Final Data "+data);
if(data.equalsIgnoreCase("{\"is_device_deleted\":true}"))
setDeviceToken(true);

mFillObject = mGson.fromJson(data, mFillObject.getClass());


} catch (Exception e) {

isOtherError = true;
e.printStackTrace();
}
}
return mFillObject;
}

/**
* Function
* Takes and keeps a reference of the passed context in order to Check whether Internet is available or not.
* @param context
* @return The return will be true if the internet is available and false if not.
*/
public boolean check_Internet()
{
mConnectivityManager= (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();

if(mNetworkInfo != null && mNetworkInfo.isConnectedOrConnecting())
{
isNetError = false;
return true;
}
else
{
isNetError = true;
return false;
}
}


public Object login( GetSecrateKey mGetFlag,String usenrname,String password ) {

nameValuePairs = new ArrayList<NameValuePair>();
  nameValuePairs.add(new BasicNameValuePair("user_email", usenrname));
nameValuePairs.add(new BasicNameValuePair("user_password", password));

return  postHttpURL(AllUrl.url+"user/login",nameValuePairs, mGetFlag);
  }

 

}

Wednesday, 25 February 2015

Android Alert Dialog with custom theme

LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompts, null);

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(new ContextThemeWrapper(context, android.R.style.Theme_Holo_Light_Dialog));
alertDialogBuilder.setView(promptsView);

final EditText mEditText=(EditText)promptsView.findViewById(R.id.editTextDialogUserInput);
alertDialogBuilder.setMessage("Test for preventing dialog close");
alertDialogBuilder.setPositiveButton("Test",
       new DialogInterface.OnClickListener()
       {
           @Override
           public void onClick(DialogInterface dialog, int which)
           {
             
           }
       });
final AlertDialog dialog = alertDialogBuilder.create();
dialog.show();
//Overriding the handler immediately after show is probably a better approach than OnShowListener as described below
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
     {          
         @Override
         public void onClick(View v)
         {
             Boolean wantToCloseDialog = false;
             if (mEditText.getText().toString().trim().equalsIgnoreCase("")) {
             wantToCloseDialog=false;
             Toast.makeText(getApplicationContext(), "Enter Desription", 2000).show();
           
}
             else {
             wantToCloseDialog=true;
}
             if(wantToCloseDialog==true)
             dialog.dismiss();
             //else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
         }
     });

Monday, 27 October 2014

SharedPreferance in Android

For Store value in Sharedpreference  

SharedPreferences myPrefs = PinActivity.this.getSharedPreferences("pinPref", MODE_WORLD_READABLE);
                    SharedPreferences.Editor prefsEditor = myPrefs.edit();
                    prefsEditor.putBoolean("pin_done", true);
                    prefsEditor.putString("pin_number", mStringPin);
                    prefsEditor.putString("pin_mail", mStringPinMail);
                    prefsEditor.commit();

For get value in Sharedpreference

SharedPreferences mSharedPreferences = getSharedPreferences("pinPref", 0);
        mStringPin=mSharedPreferences.getString("pin_number", "");
        mStringPinMail=mSharedPreferences.getString("pin_mail", "");

Monday, 15 September 2014

Hide Keyboard outside touch in android

@Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        View view = getCurrentFocus();
        boolean ret = super.dispatchTouchEvent(event);

        if (view instanceof EditText) {
            View w = getCurrentFocus();
            int scrcoords[] = new int[2];
            w.getLocationOnScreen(scrcoords);
            float x = event.getRawX() + w.getLeft() - scrcoords[0];
            float y = event.getRawY() + w.getTop() - scrcoords[1];

            if (event.getAction() == MotionEvent.ACTION_UP
     && (x < w.getLeft() || x >= w.getRight()
     || y < w.getTop() || y > w.getBottom()) ) {
                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
            }
        }
     return ret;
    }