Thursday 24 April 2014

Android - How to store value in Sqlite Database

This post is about "How to create Sqlite Database" and "How to store and retrieve value from SQlite DataBase "

Step - 1 You have to create DataBaseHanler Class .

DatabaseHandler.java


package com.androidhive.androidsqlite;

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

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

public class DatabaseHandler extends SQLiteOpenHelper {

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

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

 // Database table name
 private static final String TABLE_LIST = "MyListItem";

 // Table Columns names
 private static final String KEY_ID = "id";
 private static final String KEY_ListItem = "listitem";

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

 // Creating Tables
 @Override
 public void onCreate(SQLiteDatabase db) {
  String CREATE_LIST_TABLE = "CREATE TABLE " + TABLE_LIST + "(" + KEY_ID
    + " INTEGER," + KEY_ListItem + " TEXT" + ")";

  db.execSQL(CREATE_LIST_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_LIST);

  // Create tables again
  onCreate(db);
 }



 void addListItem(ArrayList<String> listItem) {
  SQLiteDatabase db = this.getWritableDatabase();

  ContentValues values = new ContentValues();
  for (int i = 0; i < listItem.size(); i++) {

   Log.e("vlaue inserting==", "" + listItem.get(i));
   values.put(KEY_ListItem, listItem.get(i));
   values.put(KEY_ID, i);
   db.insert(TABLE_LIST, null, values);

  }

  db.close(); // Closing database connection
 }

 Cursor getListItem() {
  String selectQuery = "SELECT  * FROM " + TABLE_LIST;

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

  return cursor;
 }

}


AndroidSQLiteTutorialActivity.java



package com.androidhive.androidsqlite;

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

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;

public class AndroidSQLiteTutorialActivity extends Activity {
 /** Called when the activity is first created. */

 ArrayList<String> your_list_arrayArrayList;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  your_list_arrayArrayList = new ArrayList<String>();

  your_list_arrayArrayList.add("Item1");
  your_list_arrayArrayList.add("Item2");
  your_list_arrayArrayList.add("Item3");
  your_list_arrayArrayList.add("Item4");
  your_list_arrayArrayList.add("Item5");

  DatabaseHandler db = new DatabaseHandler(this);

  db.addListItem(your_list_arrayArrayList);

  Cursor cursor = db.getListItem();

  Log.e("count", "" + cursor.getCount());
  if (cursor != null) {
   cursor.moveToNext();

   do {

    Log.e("value==", "" + cursor.getString(1));
    Log.e("value==", "" + cursor.getString(0));

   } while (cursor.moveToNext());

  }

 }
}


You will find created Database from following steps-
Step 1- Open DDMS
Step 2- Open File Explorer
Step 3- Click on data
Step 4- Again Explore data
Step 5- Now find you package name
Step 6- Click on database
Step 7-  Now you can see your database file's name
Step 8- Export this file in to your PC

Hope this code helps you!!!!
Happy Coding...!!!!:)





Android - How To Check Google Play Services Exist Or Not

This post is about "How to check google play services exist or not". If some devices don't have Google Play Services then how to call direct google play service update from "Google Play Market".


Sample Screen Shot - 






Step 1- You have to import google play service library in to your project explorer.
Go to - File - > Import -> Existing Android Code Into Workspace 
     
Then Click Next
Browse path for your "Android SDK Folder". 

My Path is - "D:\shweta\android-sdk-windows\android-sdk-windows\extras\google\google_play_services\libproject"

Important - Then "Check Copy Project to workspace"

Click Finish.

Now you successfully import Google Play Library in to your project explorer. 

Step -2 You have to add Google Play Library in to your project .

Go to - Right Click on your project -> Properties -> Android - >  Drag Window( Add Library) -> Select "google-play-services-lib" -> Apply -> Ok 

Now you successfully import Google Play Library in to your project.

AndroidManifest.xml


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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.googleplayservicescheckdemo.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>
        
         <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
         
    </application>

</manifest>

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dip"
        android:layout_marginTop="15dip"
        android:text="Now your device have google play services"
        android:textStyle="bold" />

</LinearLayout>

MainActivity.java


package com.example.googleplayservicescheckdemo;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;

import android.support.v7.app.ActionBarActivity;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

public class MainActivity extends ActionBarActivity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  int status = GooglePlayServicesUtil
    .isGooglePlayServicesAvailable(getApplicationContext());
  if (status == ConnectionResult.SUCCESS) {
   // Success! Do what you want

   setContentView(R.layout.activity_main);

  } else {
   AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
     MainActivity.this);

   // set title
   alertDialogBuilder.setTitle("Alert!!1");

   // set dialog message
   alertDialogBuilder
     .setMessage(
       "This Application Want To UpDate You Google Play Services App")
     .setCancelable(false)
     .setPositiveButton("Update",
       new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,
          int id) {
         callMarketPlace();
        }
       })
     .setNegativeButton("Cancle",
       new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,
          int id) {
         // if this button is clicked, just close
         // the dialog box and do nothing
         finish();
         dialog.cancel();
        }
       });

   // create alert dialog
   // AlertDialog alertDialog = alertDialogBuilder.create();

   // show it
   alertDialogBuilder.show();

  }
 }

 public void callMarketPlace() {
  try {

   startActivityForResult(
     new Intent(Intent.ACTION_VIEW,
       Uri.parse("market://details?id="
         + "com.google.android.gms")), 1);
  } catch (android.content.ActivityNotFoundException anfe) {
   startActivityForResult(new Intent(Intent.ACTION_VIEW,
     Uri.parse("https://play.google.com/store/apps/details?id="
       + "com.google.android.gms")), 1);
  }
 }

 @TargetApi(Build.VERSION_CODES.HONEYCOMB)
 @Override
 protected void onActivityResult(int arg0, int arg1, Intent arg2) {
  // TODO Auto-generated method stub
  super.onActivityResult(arg0, arg1, arg2);

  if (arg0 == 1) {

   if (Build.VERSION.SDK_INT >= 11) {
    recreate();
   } else {
    Intent intent = getIntent();
    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
    finish();
    overridePendingTransition(0, 0);

    startActivity(intent);
    overridePendingTransition(0, 0);
   }

  }

 }

}

Hope it helps you!!!!

Happy Coding....!!!!!:)

Android - How To Implement Real Time Calculator

This post is an tutorial for android development

Today we will learn how to implement "Real Time Calculator" In Android.

Sample Screen Shot -



Here is sample code -

activity_main.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter Width" />

    <EditText
        android:id="@+id/edit_width"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/actionbar_search"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:singleLine="true"
        android:text="0" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter Height" />

    <EditText
        android:id="@+id/edit_height"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/actionbar_search"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:singleLine="true"
        android:text="0" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Calculated Area" />

    <EditText
        android:id="@+id/edit_area"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/actionbar_search"
        android:editable="false"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:text="0" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Calculated Perimeter" />

    <EditText
        android:id="@+id/edit_perimeter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/actionbar_search"
        android:editable="false"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:text="0" />

</LinearLayout>

MainActivity.java


package com.example.edittextchange;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.os.Build;

public class MainActivity extends ActionBarActivity {

 EditText edit_width, edit_height, edit_area, edit_perimeter;

 double width;
 double height;
 double area;
 double perimeter;

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

  edit_area = (EditText) findViewById(R.id.edit_area);
  edit_height = (EditText) findViewById(R.id.edit_height);
  edit_width = (EditText) findViewById(R.id.edit_width);
  edit_perimeter = (EditText) findViewById(R.id.edit_perimeter);

  edit_width.addTextChangedListener(new TextWatcher() {

   @Override
   public void onTextChanged(CharSequence s, int start, int before,
     int count) {
    // TODO Auto-generated method stub

   }

   @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

    String widthString = edit_width.getText().toString();

    // convert the String into a double
    if (widthString.length() > 0) {
     width = Double.parseDouble(widthString);
    }

    // read the height out of heightEdit
    String heightString = edit_height.getText().toString();

    if (heightString.length() > 0) {
     height = Double.parseDouble(heightString);
    }

    // calculate area
    double area = calcArea();

    // calculate perimeter
    double perim = calcPerim();

    // set the label for areaText
    edit_area.setText(Double.toString(area));

    // set the label for perimText
    edit_perimeter.setText(Double.toString(perim));

   }
  });

  edit_height.addTextChangedListener(new TextWatcher() {

   @Override
   public void onTextChanged(CharSequence s, int start, int before,
     int count) {
    // TODO Auto-generated method stub

   }

   @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

    String widthString = edit_width.getText().toString();

    // convert the String into a double
    if (widthString.length() > 0) {
     width = Double.parseDouble(widthString);
    }

    // read the height out of heightEdit
    String heightString = edit_height.getText().toString();

    if (heightString.length() > 0) {
     height = Double.parseDouble(heightString);
    }

    // calculate area
    double area = calcArea();

    // calculate perimeter
    double perim = calcPerim();

    // set the label for areaText
    edit_area.setText(Double.toString(area));

    // set the label for perimText
    edit_perimeter.setText(Double.toString(perim));

   }
  });

 }

 double calcArea() {
  return width * height;
 }

 double calcPerim() {
  return 2 * width * height;
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {

  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

 @Override
 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.
  int id = item.getItemId();
  if (id == R.id.action_settings) {
   return true;
  }
  return super.onOptionsItemSelected(item);
 }

 /**
  * A placeholder fragment containing a simple view.
  */
 public static class PlaceholderFragment extends Fragment {

  public PlaceholderFragment() {
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
   View rootView = inflater.inflate(R.layout.fragment_main, container,
     false);
   return rootView;
  }
 }

}

Hope This code helps!!!!!!
Happy Coding!!!!!!!:)

Wednesday 23 April 2014

How To Unlock/Reset Android Device When Pattern Locked

This post will show you how to unlock and reset your android device lock pattern if you have forgotten your lock pattern and can remember your Google/Gmail account.
If you have synchronized your android device with Google Gmail account before then you just need to signin your Gmail account and the lock pattern will be removed, but if you have not sync your device with Gmail or you have forgotten your Gmail ID then no need to panic just follow the step below and you will reset your android device and lock pattern will be removed.


Steps  to recover lock pattern of any android device phone
  1. Switch off the phone.
  2. Now hold this buttons all together at the same time “Volume up + Home Key + Power Button” until the phone boots (if you device doesn’t have a home button just hold together volume up key and power key)
  3. Now a screen like DOS will come up with different options
  4. Use the volume key to move up and down then scroll down to “Restore Factory Defaults” or “Delete all User Data” depending on which is on your device.
  5. After clicking on the settings above, now scroll down to “Reboot System Now ” and wait for your phone to reboot.
Now your phone will reboot and all lock pattern removed.
Happy Troubleshooting !!!!! :) 

Android - How To Implement Horizontal Scroll ListView

This post about how to implment horizontal scroll view

Sample Screen Shot-


activity_horizontal_scroll_view.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" >

    <com.shwetamaaks.horizontalscrollactivity.CenterLockHorizontalScroll
        android:id="@+id/scrollView"
        android:layout_width="match_parent"
        android:layout_height="100dip"
        android:layout_alignParentBottom="true" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >
        </LinearLayout>
    </com.shwetamaaks.horizontalscrollactivity.CenterLockHorizontalScroll>

    <LinearLayout
        android:id="@+id/bottomLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/scrollView"
        android:orientation="horizontal"
        android:weightSum="2" >

        <Button
            android:id="@+id/btnPrev"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Prev" />

        <Button
            android:id="@+id/btnNext"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Next" />
    </LinearLayout>

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@id/bottomLayout"
        android:layout_alignParentTop="true"
        android:layout_centerInParent="true"
        android:textColor="#FF0000"
        />

</RelativeLayout>


news_list_item.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:background="@drawable/app_back"
    android:paddingTop="15dip"
    android:paddingBottom="15dip" >

    
    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        
        >
        
        
         <TextView
        android:id="@+id/txtNewsSource"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Title" />
         
         
         
    </LinearLayout>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Detail news" />

</LinearLayout>

CenterLockHorizontalScroll.java


package com.shwetamaaks.horizontalscrollactivity;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;


public class CenterLockHorizontalScroll extends HorizontalScrollView {

 private static final int SWIPE_MIN_DISTANCE = 5;
 private static final int SWIPE_THRESHOLD_VELOCITY = 300;
 private int mActiveFeature = 0;
 private ArrayList mItems = null;

 private GestureDetector mGestureDetector;

 private boolean mScrollable = true;

 Context context;

 int prevIndex = 0;

 public CenterLockHorizontalScroll(Context context, AttributeSet attrs) {
  super(context, attrs);
  this.context = context;
  this.setSmoothScrollingEnabled(true);

 }

 public void setAdapter(Context context, CustomListAdapter mAdapter) {

  try {
   fillViewWithAdapter(mAdapter);
  } catch (ZeroChildException e) {

   e.printStackTrace();
  }
 }

 public void setScrollingEnabled(boolean enabled) {
  mScrollable = enabled;
 }

 public boolean isScrollable() {
  return mScrollable;
 }
//
 @Override
 public boolean onTouchEvent(MotionEvent ev) {

  Log.e("on touch for centewehjt", "xfvxc");
  switch (ev.getAction()) {
  case MotionEvent.ACTION_DOWN:
   // if we can scroll pass the event to the superclass
   if (mScrollable)
    return super.onTouchEvent(ev);
   // only continue to handle the touch event if scrolling enabled
   return mScrollable; // mScrollable is always false at this point

  case MotionEvent.ACTION_MOVE:

   // if we can scroll pass the event to the superclass
   if (mScrollable)
    return super.onTouchEvent(ev);
   // only continue to handle the touch event if scrolling enabled
   return mScrollable; // mScrollable is always false at this point

  default:
   return super.onTouchEvent(ev);
  }
 }
 
 


 @Override
 public boolean onInterceptTouchEvent(MotionEvent ev) {
  // Don't do anything with intercepted touch events if
  // we are not scrollable
  if (!mScrollable)
   return false;
  else
   return super.onInterceptTouchEvent(ev);
 }

 private void fillViewWithAdapter(CustomListAdapter mAdapter)
   throws ZeroChildException {
  if (getChildCount() == 0) {
   throw new ZeroChildException(
     "CenterLockHorizontalScrollView must have one child");
  }
  if (getChildCount() == 0 || mAdapter == null)
   return;

  ViewGroup parent = (ViewGroup) getChildAt(0);

  parent.removeAllViews();

  for (int i = 0; i < mAdapter.getCount(); i++) {
   parent.addView(mAdapter.getView(i, null, parent));
  }
 }

 public void setCenter(int index) {

  ViewGroup parent = (ViewGroup) getChildAt(0);

  View preView = parent.getChildAt(prevIndex);
  android.widget.LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.WRAP_CONTENT,
    LinearLayout.LayoutParams.WRAP_CONTENT);
  lp.setMargins(5, 5, 5, 5);
  preView.setLayoutParams(lp);

  View view = parent.getChildAt(index);
  int screenWidth = ((Activity) context).getWindowManager()
    .getDefaultDisplay().getWidth();

  int scrollX = (view.getLeft() - (screenWidth / 2))
    + (view.getWidth() / 2);
  this.smoothScrollTo(scrollX, 0);
  prevIndex = index;
 }

 class MyGestureDetector extends SimpleOnGestureListener {
  @Override
  public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
    float velocityY) {
   try {
    // right to left
    if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
      && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
     int featureWidth = getMeasuredWidth();
     mActiveFeature = (mActiveFeature < (5 - 1)) ? mActiveFeature + 1
       : 5 - 1;
     smoothScrollTo(mActiveFeature * featureWidth, 0);
     return true;
    }
    // left to right
    else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
      && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
     int featureWidth = getMeasuredWidth();
     mActiveFeature = (mActiveFeature > 0) ? mActiveFeature - 1
       : 0;
     smoothScrollTo(mActiveFeature * featureWidth, 0);
     return true;
    }
   } catch (Exception e) {
    Log.e("Fling", "There was an error processing the Fling event:"
      + e.getMessage());
   }
   return false;
  }
 }

}

CustomListAdapter.java


package com.shwetamaaks.horizontalscrollactivity;

import java.util.ArrayList;

import com.example.horizontalscrollactivity.R;



import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;


public class CustomListAdapter extends ArrayAdapter<String> {
 Context context;
 private ArrayList<String> list;
 int layoutId;
 Holder holder;
 public View view;
 public int currPosition = 0;

 public CustomListAdapter(Context context, int textViewResourceId,
   ArrayList<String> list) {
  super(context, android.R.layout.simple_list_item_1, list);
  this.context = context;
  this.list = list;
  layoutId = textViewResourceId;

 }

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

 @Override
 public String getItem(int position) {
  return list.get(position);
 }

 @Override
 public View getView(final int position, View convertView, ViewGroup parent) {
  LinearLayout layout;

  if (convertView == null) {

   layout = (LinearLayout) View.inflate(context, layoutId, null);

   holder = new Holder();

   holder.title = (TextView) layout.findViewById(R.id.txtNewsSource);
   layout.setTag(holder);

  } else {
   layout = (LinearLayout) convertView;
   view = layout;
   holder = (Holder) layout.getTag();
  }
  String newsSource = getItem(position);
  holder.title.setText(newsSource);
  Log.v("Test", "lo frm newsadpater");

  return layout;
 }

 private class Holder {
  public TextView title;

 }
 public int getCurrentPosition(){
  return currPosition;
 }
}

MainActivity.java


package com.shwetamaaks.horizontalscrollactivity;

import java.util.ArrayList;

import com.example.horizontalscrollactivity.R;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;

public class MainActivity extends Activity {
 CenterLockHorizontalScroll centerLockHorizontalScrollview;
 CustomListAdapter customListAdapter;
 private GestureListener mGestureDetector;
 private static final int SWIPE_MIN_DISTANCE = 5;
 private static final int SWIPE_THRESHOLD_VELOCITY = 300;

 OnSwipeDetectListener onSwipeTouchListener;

 Button btnPrev, btnNext;
 GestureDetector gestureDetector;
 int currIndex = 0;
 private TextView text;
 ArrayList<String> list = new ArrayList<String>() {

  {
   add("Manchester city");
   add("Manchester United");
   add("Chelsea");
   add("Liverpool");
   add("TottenHam");
   add("Everton");
   add("WestHam");
   add("Arsenal");
   add("West Broom");
   add("New Castle");
   add("Norich City");
   add("Swansea city");
   add("stroke city");

  }
 };

 @TargetApi(Build.VERSION_CODES.HONEYCOMB)
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_horizontal_scroll_view);

  gestureDetector = new GestureDetector(new GestureListener());

  mGestureDetector = new GestureListener();
  btnNext = (Button) findViewById(R.id.btnNext);
  btnPrev = (Button) findViewById(R.id.btnPrev);
  text = (TextView) findViewById(R.id.text);
  centerLockHorizontalScrollview = (CenterLockHorizontalScroll) findViewById(R.id.scrollView);
  customListAdapter = new CustomListAdapter(this,
    R.layout.news_list_item, list);
  centerLockHorizontalScrollview.setAdapter(this, customListAdapter);
  btnNext.setOnClickListener(onClickListener);
  btnPrev.setOnClickListener(onClickListener);

  centerLockHorizontalScrollview.setScrollingEnabled(false);

  onSwipeTouchListener = new OnSwipeDetectListener(this) {

   public void onSwipeTop() {
    Toast.makeText(MainActivity.this, "top", Toast.LENGTH_SHORT)
      .show();
   }

   public void onSwipeRight() {
    Toast.makeText(MainActivity.this, "right", Toast.LENGTH_SHORT)
      .show();
    if (currIndex != 0) {
     currIndex--;
     centerLockHorizontalScrollview.setCenter(currIndex);
     text.setText(list.get(currIndex == 0 ? 0 : currIndex - 1));
    }
   }

   public void onSwipeLeft() {
    Toast.makeText(MainActivity.this, "left", Toast.LENGTH_SHORT)
      .show();

    if (currIndex < list.size()) {
     centerLockHorizontalScrollview.setCenter(currIndex);
     currIndex++;
     text.setText(list.get(currIndex - 1));
    }

   }

   public void onSwipeBottom() {
    Toast.makeText(MainActivity.this, "bottom", Toast.LENGTH_SHORT)
      .show();
   }

  };

  centerLockHorizontalScrollview
    .setOnTouchListener(new OnTouchListener() {

     @Override
     public boolean onTouch(View v, MotionEvent event) {
      // TODO Auto-generated method stub
      if (gestureDetector.onTouchEvent(event)) {
       return false;

      }

      return true;
     }
    });

  // centerLockHorizontalScrollview.setOnTouchListener(onSwipeTouchListener);

  // centerLockHorizontalScrollview.setOnTouchListener(new
  // OnSwipeDetectListener(this){
  //
  // public void onSwipeTop() {
  // Toast.makeText(HorizontalScrollViewActivity.this, "top",
  // Toast.LENGTH_SHORT).show();
  // }
  // public void onSwipeRight() {
  // Toast.makeText(HorizontalScrollViewActivity.this, "right",
  // Toast.LENGTH_SHORT).show();
  // }
  // public void onSwipeLeft() {
  // Toast.makeText(HorizontalScrollViewActivity.this, "left",
  // Toast.LENGTH_SHORT).show();
  // }
  // public void onSwipeBottom() {
  // Toast.makeText(HorizontalScrollViewActivity.this, "bottom",
  // Toast.LENGTH_SHORT).show();
  // }
  //
  // public boolean onTouch(View v, MotionEvent event) {
  // return true;
  // }
  //
  // });

 }

 private final class GestureListener extends SimpleOnGestureListener {
  private static final int SWIPE_THRESHOLD = 300;
  private static final int SWIPE_VELOCITY_THRESHOLD = 300;

  @Override
  public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
    float velocityY) {
   // TODO Auto-generated method stub
   boolean result = false;
   try {
    float diffY = e2.getY() - e1.getY();
    float diffX = e2.getX() - e1.getX();
    if (Math.abs(diffX) > Math.abs(diffY)) {
     if (Math.abs(diffX) > SWIPE_THRESHOLD
       && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
      if (diffX > 0) {

       Log.e("right", "------------------");
       // onSwipeRight();
      } else {
       Log.e("Left", "------------------");
      }
     }
    } else {
     if (Math.abs(diffY) > SWIPE_THRESHOLD
       && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
      if (diffY > 0) {
       // onSwipeBottom();
      } else {
       // onSwipeTop();
      }
     }
    }
   } catch (Exception exception) {
    exception.printStackTrace();
   }
   return result;
  }

 }

 OnClickListener onClickListener = new OnClickListener() {

  @Override
  public void onClick(View v) {
   if (v.getId() == R.id.btnPrev) {
    if (currIndex != 0) {
     currIndex--;
     centerLockHorizontalScrollview.setCenter(currIndex);
     text.setText(list.get(currIndex == 0 ? 0 : currIndex - 1));
    }
   } else if (v.getId() == R.id.btnNext) {

    if (currIndex < list.size()) {
     centerLockHorizontalScrollview.setCenter(currIndex);
     currIndex++;
     text.setText(list.get(currIndex - 1));
    }
   }

  }
 };

 public boolean dispatchTouchEvent(MotionEvent ev) {

  onSwipeTouchListener.getGestureDetector().onTouchEvent(ev);
  return super.dispatchTouchEvent(ev);
 };
}

OnSwipeDetectListener.java


package com.shwetamaaks.horizontalscrollactivity;

import android.content.Context;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnTouchListener;


public class OnSwipeDetectListener implements OnTouchListener {

 private GestureDetector gestureDetector;
 

 
    private boolean mScrollable = true;
    
 
 public GestureDetector getGestureDetector(){
     return  gestureDetector;
 }

 public OnSwipeDetectListener(Context con) {
  // TODO Auto-generated constructor stub
  gestureDetector = new GestureDetector(con, new GestureListener());
 }


    public void setScrollingEnabled(boolean enabled) {
        mScrollable = enabled;
    }

    public boolean isScrollable() {
        return mScrollable;
    }

    
 
 private final class GestureListener extends SimpleOnGestureListener {
  private static final int SWIPE_THRESHOLD = 100;
  private static final int SWIPE_VELOCITY_THRESHOLD = 100;

  @Override
  public boolean onDown(MotionEvent e) {
   // TODO Auto-generated method stub
   Log.e("on down on swipe gesture listener", "-->");
    switch (e.getAction()) {
             case MotionEvent.ACTION_DOWN:
                 // if we can scroll pass the event to the superclass
                 if (mScrollable) 
                  //return super.onTouchEvent(e);
                 // only continue to handle the touch event if scrolling enabled
                 return mScrollable; // mScrollable is always false at this point
             default:
                 return true;
         }
   
  }
  
  @Override
  public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
    float velocityY) {
   // TODO Auto-generated method stub
   boolean result = false;
            try {
                float diffY = e2.getY() - e1.getY();
                float diffX = e2.getX() - e1.getX();
                if (Math.abs(diffX) > Math.abs(diffY)) {
                    if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffX > 0) {
                            onSwipeRight();
                        } else {
                            onSwipeLeft();
                        }
                    }
                } else {
                    if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffY > 0) {
                            onSwipeBottom();
                        } else {
                            onSwipeTop();
                        }
                    }
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
            return result;
  }

 }
 
  public void onSwipeRight() {
     }

     public void onSwipeLeft() {
     }

     public void onSwipeTop() {
     }

     public void onSwipeBottom() {
     }

 @Override
 public boolean onTouch(View v, MotionEvent event) {
  // TODO Auto-generated method stub
  return false;
 }
 
 

}

ZeroChildException.java


package com.shwetamaaks.horizontalscrollactivity;

public class ZeroChildException extends Exception {

 private static final long serialVersionUID = 1L;

 public ZeroChildException() {

 }

 public ZeroChildException(String errorMessage) {
  super(errorMessage);
 }

}


Enjoy Coding!!!!!!

All The Best...!!!!!!:)