Monday, April 29, 2013

ImageSwitcher & UpdateTimeTask or update anythiing by some time interval




package com.droidikin.samples.imageswitcher;


import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;

public class CodeActivity extends Activity implements ViewFactory {
// A reference to the images contained into the drawable folder
private Integer[] m_ImageIds = {
            R.drawable.img_01,
            R.drawable.img_02,
            R.drawable.img_03
};

// The ImageSwitcher
ImageSwitcher m_ImageSwitcher;
// The Handler used for manage the Runnable that switch the images
Handler m_Handler = new Handler();

// The index of the current image
int m_imageIndex = 0;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.use_code_activity);
        // assign the ImageSwitcher
        m_ImageSwitcher = (ImageSwitcher)findViewById(R.id.imageswitcher);
        m_ImageSwitcher.setFactory(this);
        // Create the Fade in animation
        Animation fadeIn = AnimationUtils.loadAnimation(this, android.R.anim.fade_in);
        fadeIn.setDuration(3000);
        // Create the Fade out animation
        Animation fadeOut = AnimationUtils.loadAnimation(this, android.R.anim.fade_out);
        fadeOut.setDuration(3000);
        // Assign the two animations to the ImageSwitcher
        m_ImageSwitcher.setInAnimation(fadeIn);
        m_ImageSwitcher.setOutAnimation(fadeOut);
        
        // Start the Runnable
        m_Handler.post(m_UpdateTimeTask);        
    }

@Override
public View makeView() {
ImageView i = new ImageView(this);
i.setBackgroundColor(0xFF000000);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
return i;
}
/*
* Set the image to show into the ImageSwitcher, then post his execution after 5 seconds
*/
Runnable m_UpdateTimeTask = new Runnable() {
  public void run() 
  {
  Log.e("------run()--", " ");
  // Set the Image to show
  m_ImageSwitcher.setImageResource(m_ImageIds[m_imageIndex]);
  // Increment the index
  m_imageIndex++;
  // if necessary restart from the first image
  if(m_imageIndex > (m_ImageIds.length-1)){
  m_imageIndex = 0;
  }
  // Set the execution after 5 seconds
//   m_Handler.postDelayed(this, (5 * 1000));
  
  m_Handler.postDelayed(this, (500));
  }
};

}

android view flipper

Wednesday, April 17, 2013

google analytics example with android

json parser for android

download:  http://www.mediafire.com/?pdulzgzzw5v31fz



package com.androidhive.jsonparsing;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class AndroidJSONParsingActivity extends ListActivity {

// url to make request
private static String url = "http://api.androidhive.info/contacts/";

// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";

// contacts JSONArray
JSONArray contacts = null;

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

// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();

// Creating JSON Parser instance
JSONParser jParser = new JSONParser();

// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);

try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);

// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);

// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);

// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);

// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();

// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);

// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}


/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] {
R.id.name, R.id.email, R.id.mobile });

setListAdapter(adapter);

// selecting single ListView item
ListView lv = getListView();

// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();

// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);

}
});



}

}


JSONParser.java
-----------------------------------------------


package com.androidhive.jsonparsing;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;

}
}



SingleMenuItemActivity.java
-----------------------------------------------

package com.androidhive.jsonparsing;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class SingleMenuItemActivity  extends Activity {

// JSON node keys
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_PHONE_MOBILE = "mobile";
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.single_list_item);
     
        // getting intent data
        Intent in = getIntent();
     
        // Get JSON values from previous intent
        String name = in.getStringExtra(TAG_NAME);
        String cost = in.getStringExtra(TAG_EMAIL);
        String description = in.getStringExtra(TAG_PHONE_MOBILE);
     
        // Displaying all values on the screen
        TextView lblName = (TextView) findViewById(R.id.name_label);
        TextView lblCost = (TextView) findViewById(R.id.email_label);
        TextView lblDesc = (TextView) findViewById(R.id.mobile_label);
     
        lblName.setText(name);
        lblCost.setText(cost);
        lblDesc.setText(description);
    }
}



Tuesday, April 9, 2013

android notification


protected void updateNotification(Integer _percent, Context mContext) {

CharSequence contentText = _percent + "% complete";
// publish it to the status bar
mNotification.setLatestEventInfo(mContext, "update Download",
contentText, mContentIntent);
mNotification.icon = android.R.drawable.stat_sys_download;
mNotificationManager.notify(NOTIFICATION_ID, mNotification);

}

public void createNotification(Context mContext) {
// get the notification manager
mNotificationManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE);

// create the notification
int icon = android.R.drawable.stat_sys_download;
CharSequence tickerText = "Download"; // Initial text that appears in
// the status bar
long when = System.currentTimeMillis();
mNotification = new Notification(icon, tickerText, when);


// create the content which is shown in the notification pulldown
String mContentTitle = "progress"; // Full title of the notification in
// the pull down
CharSequence contentText = "0% complete"; // Text of the notification in
// the pull down

// you have to set a PendingIntent on a notification to tell the system
// what you want it to do when the notification is selected
// I don't want to use this here so I'm just creating a blank one
Intent notificationIntent = new Intent();
mContentIntent = PendingIntent.getActivity(mContext, 0,
notificationIntent, 0);

// add the additional content and intent to the notification
mNotification.setLatestEventInfo(mContext, mContentTitle, contentText,
mContentIntent);

// make this notification appear in the 'Ongoing events' section
mNotification.flags = Notification.FLAG_ONGOING_EVENT;

// show the notification
mNotificationManager.notify(NOTIFICATION_ID, mNotification);
}

service demo

sound service :download: http://www.mediafire.com/?2dfduknw1xkhir1

background service: http://www.mediafire.com/download/2dfduknw1xkhir1/ServicesDemo.zip


ServicesDemo.java (MainActivity)
------------------------------------------

package com.example;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ServicesDemo extends Activity implements OnClickListener {
  private static final String TAG = "ServicesDemo";
  Button buttonStart, buttonStop;

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

    buttonStart = (Button) findViewById(R.id.buttonStart);
    buttonStop = (Button) findViewById(R.id.buttonStop);

    buttonStart.setOnClickListener(this);
    buttonStop.setOnClickListener(this);
  }

  public void onClick(View src) {
    switch (src.getId()) {
    case R.id.buttonStart:
      Log.d(TAG, "onClick: starting srvice");
      startService(new Intent(this, MyService.class));
      break;
    case R.id.buttonStop:
      Log.d(TAG, "onClick: stopping srvice");
      stopService(new Intent(this, MyService.class));
      break;
    }
  }
}

MyService.java
-------------------------------


package com.example;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {
private static final String TAG = "MyService";
MediaPlayer player;

@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");

player = MediaPlayer.create(this, R.raw.moon);
player.setLooping(false); // Set looping
}

@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}

@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player.start();
}
}


main.xml
-------------------------

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="20dp"
        android:text="Services Demo"
        android:textSize="20sp" />

    <Button
        android:id="@+id/buttonStart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start" >
    </Button>

    <Button
        android:id="@+id/buttonStop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop" >
    </Button>

</LinearLayout>


mainifest.xml
------------------------------------

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

    <application
        android:icon="@drawable/icon"
        android:label="@string/app_name" >
        <activity
            android:name=".ServicesDemo"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".MyService"
            android:enabled="true" />
    </application>

    <uses-sdk android:minSdkVersion="3" />

</manifest>

led light notification

download:  http://www.mediafire.com/?4bg5mk4od4c7rg6


package com.example.ledlight;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;

public class MainActivity extends Activity
{

int NOTIFICATION_ID = 1;
int LED_ON_MS = 100;
int LED_OFF_MS = 100;

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

redFlashLight();

}

void redFlashLight() {
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notif = new Notification();
notif.ledARGB = Color.BLUE;
notif.flags = Notification.FLAG_SHOW_LIGHTS;
notif.ledOnMS = LED_ON_MS;
notif.ledOffMS = LED_OFF_MS;
nm.notify(NOTIFICATION_ID, notif);

// Program the end of the light :
Handler mCleanLedHandler = new Handler();

mCleanLedHandler.postDelayed(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub

}
}, 500);
}

void clearLED() {
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.cancel(NOTIFICATION_ID);
}

@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();

clearLED();
}

}

Friday, April 5, 2013

fragment tab paging

apk fie install from termina

$ echo $PATH ---(should return the directories associated with $PATH)

$ export PATH=$PATH:/home/YOUR-USERNAME/sdk/tools
---(replace with path to your tools directory, you may need to add 'sudo' to the beginning of this cmd)
Update: later versions of the SDK have ADB moved to the platform-tools directory, so adjust the above accordingly.


$ echo $PATH 
---(you should now see your tools directory added to the end of the $PATH variable)

$ adb devices
---(now adb should do something, if nothing else at least error, no devices)


And now I get:

List of devices attached
emulator-5554 device





uninstall cmd:   adb uninstall com.stylingandroid.viewpager

install cmd:  adb install ~/Downloads/BarcodeScanner3.6.apk

Tuesday, April 2, 2013

sqllite example from asset with crud

download: http://www.mediafire.com/?tncc0fdp360xfde


package com.example.sqlliteimport;

import java.util.ArrayList;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

CRUDonDB mCRUDonDB;

Cursor cursor;

public static ListView lvForDbData;

public static ListArrayAdapter mListArrayAdapter;

ArrayList<String> nameAl = new ArrayList<String>();
ArrayList<Integer> idAl = new ArrayList<Integer>();

Button btAdd;
EditText etInsertData;

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

lvForDbData = (ListView) findViewById(R.id.lvForDbData);
btAdd = (Button) findViewById(R.id.btAdd);
etInsertData = (EditText) findViewById(R.id.etInsertData);

mCRUDonDB = new CRUDonDB(MainActivity.this);

select_all_data();

mListArrayAdapter = new ListArrayAdapter(MainActivity.this, nameAl,
idAl);

lvForDbData.setAdapter(mListArrayAdapter);

btAdd.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
mCRUDonDB.insert_into_db(etInsertData.getText().toString().trim() );

// mListArrayAdapter = new ListArrayAdapter(MainActivity.this,
// nameAl, idAl);

select_all_data();
// lvForDbData.setAdapter(mListArrayAdapter);

mListArrayAdapter.notifyDataSetChanged();
// mListArrayAdapter.notifyDataSetInvalidated();

etInsertData.setText("");
}
});

}

void select_all_data() {
cursor = mCRUDonDB.select_all_from_db();

nameAl.clear();
idAl.clear();
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor
.getColumnIndex("name"));

Integer id = cursor.getInt(cursor.getColumnIndex("id"));

nameAl.add(name);
idAl.add(id);

} while (cursor.moveToNext());
}
}
}

}


-------------------------------------------

package com.example.sqlliteimport;

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

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

public class CRUDonDB {

String DB_PATH = "";
// String path = "/data/";
String fileName = "ani_db";
// String fileName = "MyDatabase";

private final String DB_NAME = "ani_db";
private final String TABLE_NAME = "animal_info";

// private final String DB_NAME = "ani_db";
// private final String TABLE_NAME = "animal_info";
//

Context context;
SQLiteDatabase mSQLiteDatabase = null;
ArrayList<String> results = new ArrayList<String>();
Cursor cursorForLimitQuery;

boolean exist = false;

public CRUDonDB(Context _context) {
context = _context;

// DB_PATH = context. ;

// DB_PATH = "mnt/sdcard/Download/";
DB_PATH = "/data/data/" + context.getPackageName() + "/"; 

try {

exist = checkDataBase();

if (exist == false) {
try {
// Copy the database from assests
copyDataBase();
Log.e("---", "createDatabase database created");
} catch (Exception mIOException) {
mIOException.printStackTrace();
}
} else {

Log.d("---CRUDonDB()------database already exists-----------",
" ");
}

// limit_query();

} catch (SQLiteException se) {
Log.d("-----CRUDonDB()----catch-----------", " ");
se.printStackTrace();
}

}

// Open the database, so we can query it
public boolean openDataBase() throws SQLException {
String mPath = DB_PATH + DB_NAME;
// Log.v("mPath", mPath);
mSQLiteDatabase = SQLiteDatabase.openDatabase(mPath, null,
SQLiteDatabase.CREATE_IF_NECESSARY);
// mDataBase = SQLiteDatabase.openDatabase(mPath, null,
// SQLiteDatabase.NO_LOCALIZED_COLLATORS);
return mSQLiteDatabase != null;
}

// Check that the database exists here: /data/data/your package/databases/Da
// Name
private boolean checkDataBase() {
Log.d("-----checkDataBase()----", " ");
File dbFile = new File(DB_PATH + DB_NAME);
// Log.v("dbFile", dbFile + "   "+ dbFile.exists());
return dbFile.exists();
}

// Copy the database from assets
private void copyDataBase() {
Log.d("---copyDataBase()----", " ");

InputStream mInput = null;
try {
mInput = context.getAssets().open(DB_NAME);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String outFileName = DB_PATH + DB_NAME;
OutputStream mOutput = null;
try {
mOutput = new FileOutputStream(outFileName);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] mBuffer = new byte[1024];
int mLength;
try {
while ((mLength = mInput.read(mBuffer)) > 0) {
mOutput.write(mBuffer, 0, mLength);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mOutput.flush();
mOutput.close();
mInput.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

public void insert_into_db(String _name) 
{
openDataBase();

try {
mSQLiteDatabase.execSQL(" INSERT INTO " + TABLE_NAME+ " (name) " + " Values ( " +
"'" + _name + "' )" +
";");

Log.d("---------insert_into_db()-----------", _name.toString());

} catch (SQLException e) {
Log.d("----------SQLException------------", " ");
e.printStackTrace();
}

}

public Cursor select_all_from_db() {
// Cursor cursor = mSQLiteDatabase.rawQuery("SELECT * FROM "
// + TABLE_NAME
// +" where train_type='"+train_type+"' and shoppingMallName='"+shoppingMallName+"' ORDER BY purchased desc ",
// null);

Cursor cursor = null;

try {
Log.d("----try-----select_item_from_db()-----------", " ");

openDataBase();

String sql = "select * from " + TABLE_NAME;
cursor = mSQLiteDatabase.rawQuery(sql, null);

if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String Name = cursor.getString(cursor
.getColumnIndex("name"));

Log.d("---------Name=" + Name + "-----------", " ");

} while (cursor.moveToNext());
} else {
Log.d("---------cursor==null-----------", " ");
}
}

} catch (SQLiteException se) {
se.printStackTrace();
}

return cursor;
}

public void update_info(Integer _id, String _name) {
openDataBase();
try {
mSQLiteDatabase.execSQL("update " + TABLE_NAME
+ " set name='"+_name+"' where id= '"+_id+"' " );

Log.d("----------update success------------", " ");
} catch (SQLException e) {
Log.d("----------update SQLException="
+ e.getStackTrace().toString() + "------------", " ");
}

}

public void delete_info(Integer _id) 
{
openDataBase();
try {
mSQLiteDatabase.execSQL(" delete from " + TABLE_NAME + " where id= '"+_id+"' ");

Log.d("----------delete success------------", " ");
}
catch (SQLException e)
{
Log.d("----------update SQLException="
+ e.getStackTrace().toString() + "------------", " ");
}

}

public void limit_query() {

try {
Cursor cursorLimotQuery = mSQLiteDatabase.rawQuery("SELECT * FROM "
+ TABLE_NAME + " where purchased='1' limit 2,4 ", null);

Log.d("----------limit query success------------", " ");

if (cursorLimotQuery != null) {
if (cursorLimotQuery.moveToFirst()) {
do {
String productName = cursorLimotQuery
.getString(cursorLimotQuery
.getColumnIndex("productName"));
Integer purchased = cursorLimotQuery
.getInt(cursorLimotQuery
.getColumnIndex("purchased"));

Log.d("---------productName=" + productName.toString()
+ "-----------",
"purchased=" + purchased.toString());

// results.add("" + productName + ",purchased: " +
// purchased.to);
} while (cursorLimotQuery.moveToNext());
}
// SELECT * FROM `your_table` LIMIT 0, 10

}
} catch (SQLException e) {
Log.d("----------limit query Exception="
+ e.getStackTrace().toString() + "------------", " ");
}

}

public void close_db() {
openDataBase();
mSQLiteDatabase.close();
}

}

--------------------------------------------------
package com.example.sqlliteimport;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ListArrayAdapter extends BaseAdapter {
Context context;

TextView tvName, tvId;
Button btDelete, btEdit;

ArrayList<String> nameAl = new ArrayList<String>();

ArrayList<Integer> idAl = new ArrayList<Integer>();

CRUDonDB mCRUDonDB;

Cursor cursor;

ListArrayAdapter mListArrayAdapter;

ListView lvForDbData;

public ListArrayAdapter(Context _myContext, ArrayList<String> _nameAl,
ArrayList<Integer> _idAl) {
context = _myContext;

nameAl = _nameAl;
idAl = _idAl;

}

@Override
public int getCount() // number of item in gridView
{
return nameAl.size();
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View myView = convertView;
final Integer positionInteger = position + 1;

if (convertView == null) {
LayoutInflater li = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
myView = li.inflate(R.layout.list_item, null);
}

tvName = (TextView) myView.findViewById(R.id.tvName);

tvId = (TextView) myView.findViewById(R.id.tvId);
btDelete = (Button) myView.findViewById(R.id.btDelete);
btEdit = (Button) myView.findViewById(R.id.btEdit);

tvName.setText(nameAl.get(position).toString());
tvId.setText(idAl.get(position).toString());

btDelete.setOnLongClickListener(new OnLongClickListener() {

@Override
public boolean onLongClick(View v) {

Toast.makeText(context, "deleted".toString(),
Toast.LENGTH_SHORT).show();

mCRUDonDB = new CRUDonDB(context);
mCRUDonDB.delete_info((Integer) idAl.get(position));
select_all_data();

MainActivity.mListArrayAdapter.notifyDataSetChanged();
// MainActivity.mListArrayAdapter.notifyDataSetInvalidated();

return false;
}
});
btEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) 
{
final AlertDialog.Builder alert = new AlertDialog.Builder(context);
   final EditText input = new EditText(context);
   input.setHint("edit '" + nameAl.get(position).toString() + "' ?");
   alert.setView(input);
   alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int whichButton) {
           String value = input.getText().toString().trim();
           
           if(!input.getText().toString().equals(""))
           {
            mCRUDonDB = new CRUDonDB(context);
mCRUDonDB.update_info(idAl.get(position), input.getText().toString().trim() );
select_all_data();
MainActivity.mListArrayAdapter.notifyDataSetChanged();
           }
// MainActivity.mListArrayAdapter.notifyDataSetInvalidated();
       }
   });

   alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int whichButton) {
           dialog.cancel();
       }
   });
   alert.show();  
}
});

return myView;
}

void select_all_data() {
cursor = mCRUDonDB.select_all_from_db();

nameAl.clear();
idAl.clear();
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor
.getColumnIndex("name"));

Integer id = cursor.getInt(cursor.getColumnIndex("id"));

nameAl.add(name);
idAl.add(id);

} while (cursor.moveToNext());
}
}
}

@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}

@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}

}

-----------------------------------
main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ListView
        android:id="@+id/lvForDbData"
        android:layout_width="fill_parent"
        android:layout_height="300dp" >
    </ListView>

    <EditText
        android:id="@+id/etInsertData"
        android:layout_width="200dp"
        android:layout_height="50dp"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/lvForDbData"
        android:layout_marginTop="52dp"
        android:ems="10"
        android:hint="Add data" >

        <requestFocus />
    </EditText>
    
    <Button
        android:id="@+id/btAdd"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/etInsertData"
        android:layout_marginRight="14dp"
        android:layout_toRightOf="@+id/etInsertData"
        android:text="Add" />

</RelativeLayout>

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

    <TextView
        android:id="@+id/tvId"
        android:gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="28dp"
        android:text="id" />

    <TextView
        android:id="@+id/tvName"
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:layout_alignBaseline="@+id/tvId"
        android:layout_alignBottom="@+id/tvId"
        android:layout_toRightOf="@+id/tvId"
        android:gravity="center"
        android:paddingRight="10dip"
        android:text="Country Abbrev" />

    <Button
        android:id="@+id/btDelete"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_alignBottom="@+id/tvId"
        android:layout_alignParentRight="true"
        android:layout_marginRight="19dp"
        android:background="@drawable/close"
        android:gravity="center"
        android:layout_marginBottom="5dp" />

    <Button
        android:id="@+id/btEdit"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_alignBaseline="@+id/btDelete"
        android:layout_alignBottom="@+id/btDelete"
        android:layout_marginRight="23dp"
        android:layout_toLeftOf="@+id/btDelete"
        android:background="@drawable/edit" />

</RelativeLayout>