Friday, September 16, 2011

Database

Step 1:


public class DataCoupon{

private static final String DATABASE_CREATE =
"create table ram (1 integer primary key, "
+ "2 text,3 text not null,4 text);";

private final Context context;

private DatabaseHelper DBHelper;
private SQLiteDatabase db;

private static final String DATABASE_NAME = "data";
private static final String DATABASE_TABLE = "ram";
private static final int DATABASE_VERSION = 1;
private static final String TAG = "database";

public DataCoupon(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}

public void deleteAll() {
db.delete(DATABASE_TABLE, null, null);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DATABASE_CREATE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");

db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE);
onCreate(db);
}

}

/**---opens the database---*/
public DataCoupon open() throws SQLException
{

db = DBHelper.getWritableDatabase();
return this;
}

/**---closes the database---*/
public void close()
{
DBHelper.close();
}

/**---deletes a particular title---*/
public boolean deleteFeed(long Story_id)
{
return db.delete(DATABASE_TABLE, "Story_id" +
"=" + Story_id, null) > 0;
}

/**---insert a title into the database---
* @param date
* @param avgMealForTwo */

public long insert(int 1, String 2, String 3, String 4){

ContentValues initialValues = new ContentValues();
initialValues.put("1", 1);
initialValues.put("2", 2);
initialValues.put("3", 3);
initialValues.put("4", 4);
return db.insert(DATABASE_TABLE, null, initialValues);

}

/**---Get multiValue Result of user Query--g*/
public Cursor multiValueQuery(String userSQL){
Cursor cursorResult=null;
try{
cursorResult=db.rawQuery(userSQL, null);


}catch(Exception e){
System.out.println("Error in select all--"+e);
return null;
}
if (cursorResult != null) {
cursorResult.moveToFirst();
}
return cursorResult;
}



/**-- Give a single value as result for our give query in compileStatement--g*/
public SQLiteStatement singleValueQuery(String userSQL){
SQLiteStatement result=null;
try{

result=db.compileStatement(userSQL);

return result;

}catch(Exception e){
System.out.println("User Query Error"+e);
return null;
}
}

//---retrieves a particular title---
public Cursor getFeed(Integer 1) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {
"1",
"2",
"3",
"4"
},
"1" + "=" + 1,
null,
null,
null,
null,
null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}


}


Step 2:

DataCoupon saved;

saved=new DataCoupon(this);
saved.open();
Cursor res=saved.getFeed(id);
if(res==null || res.getCount()<=0){
saved.open();
try{
saved_coupon.insert(id,2,3,4);
}catch (Exception e) {
Log.e("tag", "Error while Querying - "+e);
}
saved.close();

Toast.makeText(this, "downloaded", Toast.LENGTH_SHORT).show();

res.close();
}
else{
Toast.makeText(getApplicationContext(), "This already downloaded", Toast.LENGTH_SHORT).show();
res.close();
}
saved.close();

Wednesday, September 14, 2011

Style Theme







, separater android

URL url=new URL("url");

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String reader = "";
String[] RowData=null;
while ((reader = in.readLine()) != null){
RowData = reader.split(",");

for(String temp:RowData){
GlobleVariable.list.add(temp);
}

Asyn Parser

Step 1:

package com.parser;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;


public abstract class BaseFeedParser implements FeedParser {

private final URL feedUrl1;

protected BaseFeedParser(String feedUrl){
try {
this.feedUrl1 = new URL(feedUrl);
} catch (MalformedURLException e) {
throw new RuntimeException("BasefeedParser wrong url /n"+e);
}
}

protected InputStream getInputStream() {
try {
return feedUrl1.openConnection().getInputStream();
} catch (IOException e) {
throw new RuntimeException("connection failed IO exp "+e);
}

}
}




Step 2:




import java.util.List;

public interface FeedParser {


List parse();

}


Step 3:


public class FeedParserFactory {

static String feedUrl = "";
public FeedParserFactory(String url){

feedUrl=url;
}
public FeedParser getParser(){
return getParser(PARSERType.XML_HOME);
}

public FeedParser getParser(PARSERTypetype){
switch (type) {

case 1:
return new XmlParser(feedUrl);

default:
return null;
}

}
}

Step 4:

public enum PARSERType{

1;

}

Step 5:


public class message {

private String 1="";

public String get1(){
return 1;
}
public void set1(String 1){
this.1=1;
}

Step 6:

package com.parser;

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

import org.xmlpull.v1.XmlPullParser;

import android.util.Log;
import android.util.Xml;

public class XmlParserHomePage extends BaseFeedParser {

public XmlParserHomePage(String feedUrl) {
// TODO Auto-generated constructor stub
super(feedUrl);
}
public List parse() {
// TODO Auto-generated method stub
List messages = null;
XmlPullParser parser = Xml.newPullParser();
try {
parser.setInput(getInputStream(), null);
int eventType = parser.getEventType();
message currentMessage = null;
boolean done = false;
while (eventType != XmlPullParser.END_DOCUMENT && !done){
String name = null;
switch (eventType){
case XmlPullParser.START_DOCUMENT:
messages = new ArrayList();
break;
case XmlPullParser.START_TAG:
name = parser.getName();
if (name.equalsIgnoreCase("1")){
currentMessage = new message();
} else if (currentMessage != null){
if(name.equalsIgnoreCase("2")){
currentMessage.set1(parser.nextText());
}else if(name.equalsIgnoreCase("3")||name.equalsIgnoreCase("4")){
currentMessage.set2(parser.nextText());
}else if(name.equalsIgnoreCase("5")||name.equalsIgnoreCase("6")){
currentMessage.set3(parser.nextText());
}else if(name.equalsIgnoreCase("distance")){
currentMessage.set4o(parser.nextText());
}
}
break;
case XmlPullParser.END_TAG:
name = parser.getName();
if (name.equalsIgnoreCase("1")&& currentMessage != null){
messages.add(currentMessage);
}
else if(name.equalsIgnoreCase("0")){
done = true;
}
break;
}
eventType = parser.next();
}
} catch (Exception e) {
Log.e("Error Mian PullFeedParser", e.getMessage(), e);
//throw new RuntimeException(e);

}
//return messages;
System.out.println("Pass ctrl 2 Main");
return messages;

}

@Override
public List parsecoupen() {
// TODO Auto-generated method stub
return null;
}


}


Step 7:

private void loadparser(PARSERType type) {

try{

new DataProviderCoupon().execute(type);

}catch(Exception e){
ProgressCancel();
System.out.println("Error in Main Load feed method");
}
}

class DataProviderCoupon extends AsyncTask<>{

@Override
protected List doInBackground(PARSERType... params) {

FeedParserFactory f=new FeedParserFactory(url);
FeedParser parser = f.getParser(params[0]);
List messages=parser.parse();

return messages;
}
@Override
protected void onPostExecute(List messages) {

try{
}

catch(Exception e){

System.out.println("Error in getting data...."+e);

}

super.onPostExecute(messages);
}
}


final Handler mHandler = new Handler();

final Runnable mUpdateResults = new Runnable() {
public void run() {

updateUIwithData();

}
};

Tuesday, August 23, 2011

ImageView Zoom and Scroll

http://blog.sephiroth.it/2011/04/04/imageview-zoom-and-scroll/
http://www.anddev.org/large_image_scrolling_using_low_level_touch_events-t11182.html

Friday, July 22, 2011

Thursday, July 21, 2011

sample code : drag and drop and animation view's

http://code.google.com/p/myandroidwidgets/source/browse/#svn%2Ftrunk%2FFlipAnimatorExample%253Fstate%253Dclosed

Wednesday, July 20, 2011

ReflectedImageLoader

public class ReflectedImageLoader {

//the simplest in-memory cache implementation. This should be replaced with something like SoftReference or BitmapOptions.inPurgeable(since 1.6)
private HashMap cache=new HashMap();
final String TAG="ReflectedImageLoader";
private File cacheDir;

public ReflectedImageLoader(Context context){

//Make the background thead low priority. This way it will not affect the UI performance
photoLoaderThread.setPriority(Thread.NORM_PRIORITY+3); //changed the thread priority

//Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"sample/categories");
else
cacheDir=context.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
}

final int stub_id=R.drawable.icon;
public void DisplayImage(String url, Activity activity, ImageView imageView)
{
Log.e(TAG, "URL for image loading - "+url);

url=url.replace("https", "http");

if(cache.containsKey(url)){
imageView.setImageBitmap(cache.get(url));
Log.e(TAG, "IMG Available");
System.gc();
//this.stopThread();
}else
{
Log.e(TAG, "Put on Queue");

queuePhoto(url, activity, imageView);
imageView.setImageResource(stub_id);
}

}

private void queuePhoto(String url, Activity activity, ImageView imageView)
{
//This ImageView may be used for other images before. So there may be some old tasks in the queue. We need to discard them.
photosQueue.Clean(imageView);
PhotoToLoad p=new PhotoToLoad(url, imageView);
synchronized(photosQueue.photosToLoad){
photosQueue.photosToLoad.push(p);
photosQueue.photosToLoad.notifyAll();
}

//start thread if it's not started yet
if(photoLoaderThread.getState()==Thread.State.NEW)
photoLoaderThread.start();
}

private Bitmap getBitmap(String url)
{
//I identify images by hashcode. Not a perfect solution, good for the demo.
String filename=String.valueOf(url.hashCode());
File f=new File(cacheDir, filename);

//from SD cache
Bitmap b = decodeFile(f);
if(b!=null)
return b;

//from web
try {

Bitmap bitmap=null;

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
httpget.setHeader("Accept","text/html");
httpget.setHeader("Accept-Encoding","gzip,deflate");
HttpResponse response;
try {


response = httpclient.execute(httpget);

HttpEntity entity = response.getEntity();
Log.e(TAG, "StatusCode() "+response.getStatusLine().getStatusCode());
if(entity==null||response.getStatusLine().getStatusCode()==404){
Log.e(TAG, "Empty Response for "+url);
return null;
}
InputStream is = entity.getContent();


// InputStream is=new URL(url).openStream();

Friday, July 15, 2011

Ticker

Ticker Method in MAinClass:

Gallery tickerGallery;
TimerThread timer;
Timer delay;
int sizeint=0,TickerLength=0;
int j=0;
boolean tickerLengthCalculated=false;
boolean pauseFlag=false,firstLoadFlag=false;

public void updateUIwithDataTicker() {

try{

tickerGallery.setAdapter(new custom_tickermessage(Aajtak.this,ticker_title,ticker_image));
tickerLengthCalculated=true;

tickerGallery.setFocusable(true);
tickerGallery.setFocusableInTouchMode(true);

timer = new TimerThread();
delay = new Timer();
delay.schedule(timer,30000, 30000);

}catch(Exception e){

Log.e(tag,"Error in updateUIwithDataTicker"+e);

}
}
};


class TickerLengthThread extends TimerTask{
@Override
public void run() {


this.cancel();
TickerLength=0;

tickerLengthCalculated=true;

}
}


/*
* Activity Pause and Resume
* =========================================================================================
*/
@Override
public void onPause(){
if(tickerLengthCalculated){
try {
pauseFlag=true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
super.onPause();

}
@Override
public void onResume(){

try {
if(pauseFlag)
if(tickerLengthCalculated){
pauseFlag=false;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onResume();

}

@Override
public void onDestroy(){
if(tickerLengthCalculated){
delay.cancel();
timer.cancel();
}

super.onDestroy();
}
class TimerThread extends TimerTask{
@Override
public void run() {
mHandler.post(mUpdateTicker1);

}
}

final Runnable mUpdateTicker1 = new Runnable() {
public void run() {
RefreshTicket();
if(TickerLength {

++TickerLength;
tickerGallery.setSelection(TickerLength);
}


}
};

/**
* Method to call Parser and cancel working timer Thread.
*/
private void RefreshTicket()
{
if(tickerLengthCalculated){
if(TickerLength>=ticker_size-1)
{
timer.cancel();
delay.cancel();

mHandler.post(mUpdateResultsTicker);
}

}
}

Custom Adaspter:


public class custom_tickermessage extends BaseAdapter {

ImageLoader imageLoader;
LayoutInflater myInflater;
private Activity activity;
String[] txt_title,image;
public custom_tickermessage(Activity a, String[] txt_title,String[] image) {
// TODO Auto-generated constructor stub
activity = a;
// TODO Auto-generated constructor stub
myInflater=LayoutInflater.from(a);

this.txt_title=txt_title;
this.image=image;

imageLoader=new ImageLoader(activity.getApplicationContext());
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return this.txt_title.length;
}




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

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

@Override
public View getView(int position, View vi, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if(vi==null)
{
vi = myInflater.inflate(R.layout.hometickermessage, null);
holder=new ViewHolder();

holder.image=(ImageView)vi.findViewById(R.id.tic_image);
holder.head=(TextView)vi.findViewById(R.id.tic_message);

vi.setTag(holder);
}
else
{
holder=(ViewHolder)vi.getTag();
}
holder.head.setText(txt_title[position]);
holder.image.setTag(image[position]);

imageLoader.DisplayImage(image[position], activity, holder.image);

return vi;
}

class ViewHolder{

ImageView image;
TextView head;
}


}


Layout:



android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#6E6464"
>
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
android:layout_width="100dip"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginTop="2dip"
android:layout_marginBottom="2dip"
android:id="@+id/tic_image"
/>
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFF"
android:textSize="14dip"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/tic_image"
android:id="@+id/tic_message"
/>





Main Class Layout:

android:layout_width="fill_parent"
android:layout_height="40dip"
android:background="#ABEEF5"
android:id="@+id/top_rel2"
android:layout_below="@id/top_rel"
>
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="none"
android:id="@+id/gallery_ticker"
android:spacing="2dip"
android:gravity="center_vertical"
android:fadingEdge="none"
/>

Thursday, July 14, 2011

Prev and Next msg

Onclick:



String split="";String[] split_value=null;

split=(String) v.getTag();

split_value=split.split("<>");

msg_cureentposition=Integer.parseInt(split_value[1]);

Bundle bundle=new Bundle();
Intent intent=new Intent(Aajtak.this,news_Details.class);

if(msg_cureentposition==msg_length-1)
bundle.putBoolean("nextFlag",false);
else
bundle.putBoolean("nextFlag",true);

if(msg_cureentposition==0)
bundle.putBoolean("previousFlag",false);
else
bundle.putBoolean("previousFlag",true);

bundle.putString("storyId",split_value[0]);
intent.putExtras(bundle);
startActivityForResult(intent, 100);



OnActivity:


/**
* OnActivity Result to handle All Child Activity Returned result
*/

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

if(resultCode==202){
//Next
msg=url[++msg_cureentposition];

Intent i=new Intent(Aajtak.this,news_Details.class);

Bundle bundle = new Bundle();
if(msg_cureentposition==msg_length-1)
bundle.putBoolean("nextFlag",false);
else
bundle.putBoolean("nextFlag",true);

if(msg_cureentposition==0)
bundle.putBoolean("previousFlag",false);
else
bundle.putBoolean("previousFlag",true);

bundle.putString("storyId",msg);
i.putExtras(bundle);
startActivityForResult(i,100);


}else if(resultCode==201){
//Previous

msg=url[--msg_cureentposition];
Intent i=new Intent(Aajtak.this,news_Details.class);
Bundle bundle = new Bundle();

if(msg_cureentposition==msg_length-1)
bundle.putBoolean("nextFlag",false);
else
bundle.putBoolean("nextFlag",true);

if(msg_cureentposition==0)
bundle.putBoolean("previousFlag",false);
else
bundle.putBoolean("previousFlag",true);

bundle.putString("storyId",msg);
i.putExtras(bundle);
startActivityForResult(i,100);


}
}
}



Next Class;

next.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(next_flag)
{

previous.setVisibility(View.VISIBLE);
setResult(202);
finish();
}else{
next.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(), "Last News", Toast.LENGTH_SHORT).show();
}
}

});
previous.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if( pre_flag)
{
next.setVisibility(View.VISIBLE);
setResult(201);
finish();
}else{
previous.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(), "First News", Toast.LENGTH_SHORT).show();
}
}
});

Text in WebView

web_des.setBackgroundColor(Color.BLACK);
web_des.loadData(""+StringMethods.URLencode(longdescription)+"",
mimeType, encoding);

Tuesday, July 12, 2011

Android Gps Setting Intent

http://www.androidpeople.com/android-check-gps-enabled-or-not

ImageLoader

https://github.com/thest1/LazyList

Intent.ACTION_SEND

Intent intent = new Intent(Intent.ACTION_SEND);
//intent.setType("application/octet-stream");
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, shareText);
intent.putExtra(Intent.EXTRA_TEXT, "Message: "+shareText+" - "+shareUrl);
Intent mailer = Intent.createChooser(intent, null);
startActivity(mailer);

Monday, July 11, 2011

Prev and Next msg

onActivityResult:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

if(resultCode==202){
//Next

msg=msg_id1[++msg_cureentposition];
Intent i=new Intent(details.this,details1.class);
Bundle bundle = new Bundle();
if(msg_cureentposition==msg_length-1)
bundle.putBoolean("nextFlag",false);
else
bundle.putBoolean("nextFlag",true);

if(msg_cureentposition==0)
bundle.putBoolean("previousFlag",false);
else
bundle.putBoolean("previousFlag",true);
bundle.putString("ID",msg);
i.putExtras(bundle);
startActivityForResult(i,100);


}else if(resultCode==201){
//Previous

msg=msg_id1[--msg_cureentposition];
Intent i=new Intent(details.this,details1.class);
Bundle bundle = new Bundle();

if(msg_cureentposition==msg_length-1)
bundle.putBoolean("nextFlag",false);
else
bundle.putBoolean("nextFlag",true);

if(msg_cureentposition==0)
bundle.putBoolean("previousFlag",false);
else
bundle.putBoolean("previousFlag",true);

bundle.putString("ID",msg);
i.putExtras(bundle);
startActivityForResult(i,100);


}

}



LIstCiew onClickListner:


msg_length=msg_id1.length;
list.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView arg0, View arg1,
int pos, long arg3) {
// TODO Auto-generated method stub

Intent i=new Intent(details.this,details1.class);
msg_cureentposition=pos;
Bundle bundle = new Bundle();
if(msg_cureentposition==msg_length-1)
bundle.putBoolean("nextFlag",false);
else
bundle.putBoolean("nextFlag",true);

if(msg_cureentposition==0)
bundle.putBoolean("previousFlag",false);
else
bundle.putBoolean("previousFlag",true);

bundle.putString("ID",msg_id1[pos]);
i.putExtras(bundle);
startActivityForResult(i,100);


}
});


Prev ANd Next Button:


next.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(next_flag)
{

previous.setVisibility(View.VISIBLE);
setResult(202);
finish();
}else{
next.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(), "Last News", Toast.LENGTH_SHORT).show();
}
}

});
previous.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if( pre_flag)
{
next.setVisibility(View.VISIBLE);
setResult(201);
finish();
}else{
previous.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(), "First News", Toast.LENGTH_SHORT).show();
}
}
});

Thursday, July 7, 2011

UrlEncode

public class Extras {

public static String URLencode(String s){
if (s!=null) {
StringBuffer tmp = new StringBuffer();
int i=0;
try {
//s=java.net.URLEncoder.encode(s,"UTF-8");

while (true) {
int b = (int)s.charAt(i++);
if ((b>=0x30 && b<=0x39) || (b>=0x41 && b<=0x5A) || (b>=0x61 && b<=0x7A)) {
tmp.append((char)b);
}
else {
tmp.append("%");
if (b <= 0xf) tmp.append("0");
tmp.append(Integer.toHexString(b));
}
}

}

catch (Exception e) {
}

return tmp.toString();
}

return null;
}


public static String removecommas(String str)
{
try{
if(str.contains(","))
{
str=str.replace(",","");

return str;
}

else
return str;

}catch(Exception e){
return null;
}

}


public static String removeminus(String str)
{
try{
if(str.contains("-"))
{
str=str.replace("-","");
return str;
}
else
return str;


}catch(Exception e){
return null;
}

}
}

Monday, July 4, 2011

Andriod get image from Url

ImageView iv = new ImageView(context);

try{
String url1 = "http:///test/abc.jpg";
URL ulrn = new URL(url1);
HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
InputStream is = con.getInputStream();
Bitmap bmp = BitmapFactory.decodeStream(is);
if (null != bmp)
iv.setImageBitmap(bmp);
else
System.out.println("The Bitmap is NULL");

}catch(Exception e){}
}

Friday, July 1, 2011

Db to get ID

db=new DataHelper(EatOut_details.this);
db.open();
Cursor res=db.getFeed(Story_id);

if(res==null || res.getCount()<=0){

btn_favourite.setBackgroundResource(R.drawable.added);
try{
db.insert(Story_id,1,2,3,4,5,sub_6);
}catch (Exception e) {
Log.e("1", "Error while Querying - "+e);
}

Toast.makeText(this, " dded", Toast.LENGTH_SHORT).show();

res.close();

}else{

btn_favourite.setBackgroundResource(R.drawable.icon);

try{
db.deleteFeed(Story_id);
}catch (Exception e) {
Log.e("ram", "Error while Querying - "+e);

}
Toast.makeText(this, " Removed", Toast.LENGTH_SHORT).show();
res.close();
}
db.close();

remove db

DataHelper db=new DataHelper(this);

db.open();

try{
db.deleteFeed(Story_id[select_pos]);
}catch (Exception e) {
Log.e("BookUrTable", "Error while Querying - "+e);

}

db.close();

Get Database Data

private void UpdateDatabaseEatoutDetails() {

try{

DataHelper db=new DataHelper(this);

db.open();

Cursor sqlResult=null;

sqlResult=db.multiValueQuery("select Story_id,1,2,3,4," +
"5,6,sub_location from ram");

db.close();

List 1= new ArrayList();
List 2= new ArrayList();
List 3=new ArrayList();

if (sqlResult.moveToFirst()) {
do {
Story_id1.add(sqlResult.getInt(0));
2.add(sqlResult.getString(1));
3.add(sqlResult.getString(2));
} while (sqlResult.moveToNext());
sqlResult.close();
}


if(sqlResult!=null){

size=offer1.size();

1=new String[size];
Story_id=new int[size];
2=new String[size];


for(int i=0;i {

1[i]=rating1.get(i);
Story_id[i]=Story_id1.get(i);

}
}

mHandlerOrderin.post(mUpdateResultsorderin);

}catch(Exception e){
System.out.println("=====error update db===="+e);
}

}



final Handler mHandlerOrderin = new Handler();

final Runnable mUpdateResultsorderin = new Runnable() {
public void run() {
updateUIwithDataOrderin();
}
};

DataBase android

package com.ram.database;


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



public class DataCoupon{

private static final String DATABASE_CREATE =
"create table ram1(Story_id integer primary key, "
+ "offer textt,name text not null,date text);";

private final Context context;

private DatabaseHelper DBHelper;
private SQLiteDatabase db;


private static final String DATABASE_NAME = "ram";
private static final String DATABASE_TABLE = "ram1";
private static final int DATABASE_VERSION = 1;
private static final String TAG = "ramdb";

public DataCoupon(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}

public void deleteAll() {
db.delete(DATABASE_TABLE, null, null);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DATABASE_CREATE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");

db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE);
onCreate(db);
}

}

/**---opens the database---*/
public DataCoupon open() throws SQLException
{

db = DBHelper.getWritableDatabase();
return this;
}

/**---closes the database---*/
public void close()
{
DBHelper.close();
}

/**---deletes a particular title---*/
public boolean deleteFeed(long Story_id)
{
return db.delete(DATABASE_TABLE, "Story_id" +
"=" + Story_id, null) > 0;
}

/**---insert a title into the database---
* @param date
* @param avgMealForTwo */

public long insert(int Story_id, String offer, String name, String date){

ContentValues initialValues = new ContentValues();
initialValues.put("Story_id", Story_id);
initialValues.put("offer", offer);
initialValues.put("name", name);
initialValues.put("date", date);
return db.insert(DATABASE_TABLE, null, initialValues);

}

/**---Get multiValue Result of user Query--g*/
public Cursor multiValueQuery(String userSQL){
Cursor cursorResult=null;
try{
cursorResult=db.rawQuery(userSQL, null);


}catch(Exception e){
System.out.println("Error in select all--"+e);
return null;
}
if (cursorResult != null) {
cursorResult.moveToFirst();
}
return cursorResult;
}



/**-- Give a single value as result for our give query in compileStatement--g*/
public SQLiteStatement singleValueQuery(String userSQL){
SQLiteStatement result=null;
try{

result=db.compileStatement(userSQL);

return result;

}catch(Exception e){
System.out.println("User Query Error"+e);
return null;
}
}

//---retrieves a particular title---
public Cursor getFeed(Integer Story_id) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {
"Story_id",
"offer",
"name",
"date"
},
"Story_id" + "=" + Story_id,
null,
null,
null,
null,
null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}


}

Friends Blog all sample code

http://smartandroidians.blogspot.com/2010/05/reading-and-writing-to-file-in-android.html

Wednesday, May 18, 2011

Monday, May 16, 2011

DataBase

DataHelper:

package com.jeeva.favourite;


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



public class DataHelper {

//DataBase table Create Statement
private static final String DATABASE_CREATE =
"create table ram (Story_id integer primary key, "
+ "name text not null);";

private final Context context;

private DatabaseHelper DBHelper;
private SQLiteDatabase db;


private static final String DATABASE_NAME = "ramdb";
private static final String DATABASE_TABLE = "ram";
private static final int DATABASE_VERSION = 1;
private static final String TAG = "DBAdapter";

public DataHelper(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}


private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DATABASE_CREATE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");

db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE);
onCreate(db);
}

}

/**---opens the database---*/
public DataHelper open() throws SQLException
{

db = DBHelper.getWritableDatabase();
return this;
}

/**---closes the database---*/
public void close()
{
DBHelper.close();
}

/**---deletes a particular title---*/
public boolean deleteFeed(long Story_id)
{
return db.delete(DATABASE_TABLE, "Story_id" +
"=" + Story_id, null) > 0;
}

/**---insert a title into the database---
* @param avgMealForTwo */

public long insert(int Story_id, String offer){

ContentValues initialValues = new ContentValues();
initialValues.put("Story_id", Story_id);
initialValues.put("offer", offer);

return db.insert(DATABASE_TABLE, null, initialValues);

}

/**---Get multiValue Result of user Query--g*/
public Cursor multiValueQuery(String userSQL){
Cursor cursorResult=null;
try{
cursorResult=db.rawQuery(userSQL, null);


}catch(Exception e){
System.out.println("Error in select all--"+e);
return null;
}
if (cursorResult != null) {
cursorResult.moveToFirst();
}
return cursorResult;
}



/**-- Give a single value as result for our give query in compileStatement--g*/
public SQLiteStatement singleValueQuery(String userSQL){
SQLiteStatement result=null;
try{

result=db.compileStatement(userSQL);

return result;

}catch(Exception e){
System.out.println("User Query Error"+e);
return null;
}
}

//---retrieves a particular title---
public Cursor getFeed(Integer Story_id) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {
"Story_id",
"offer",

},
"Story_id" + "=" + Story_id,
null,
null,
null,
null,
null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}


}




OPenDb:

DataHelper db;

private void UpdateDatabaseDetails() {
try{
db=new DataHelper(this);
db.open();
Cursor sqlResult=null;

sqlResult=db.multiValueQuery("select Story_id,offer from BookUrTable");
db.close();

}
}
List name1 = new ArrayList();

if (sqlResult.moveToFirst()) {
do {
Story_id1.add(sqlResult.getInt(0));
} while (sqlResult.moveToNext());
sqlResult.close();

if(sqlResult!=null){

size=offer1.size();

rating=new String[size];

Connect Db:

DataHelper db;
long res=-1;
db=new DataHelper(getParent());
db.open();
try{
db.insert(Story_id,offer);
res=db.singleValueQuery("select count(*) from BookUrTable where Story_id="+Story_id).simpleQueryForLong();
}catch (Exception e) {
Log.e("Dosa", "Error while Querying - "+e);
res=-1;
}
db.close();
Toast.makeText(getParent(), "Added", Toast.LENGTH_SHORT).show();
}

Sunday, May 8, 2011

ActivityGroup

package com.example.myandroid;

import java.util.ArrayList;

import android.app.ActivityGroup;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;

public class FirstGroup extends ActivityGroup {

// Keep this in a static variable to make it accessible for all the nested activities, lets them manipulate the view
public static FirstGroup group;

// Need to keep track of the history if you want the back-button to work properly, don't use this if your activities requires a lot of memory.
private ArrayList history;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.history = new ArrayList();
group = this;

// Start the root activity withing the group and get its view
View view = getLocalActivityManager().startActivity("CitiesActivity", new
Intent(this,CitiesActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();

// Replace the view of this ActivityGroup
replaceView(view);

}

public void replaceView(View v) {
// Adds the old one to history
history.add(v);
// Changes this Groups View to the new View.
setContentView(v);
}

public void back() {
if(history.size() > 0) {
history.remove(history.size()-1);
setContentView(history.get(history.size()-1));
}else {
finish();
}
}

// public void onBackPressed() {
// FirstGroup.group.back();
// return;
// }
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if(keyCode==KeyEvent.KEYCODE_BACK){
back();
return true;
}else

return super.onKeyDown(keyCode, event);
}
}






Add Code:
View view = FirstGroup.group.getLocalActivityManager()
.startActivity("show_city", i
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();

// Again, replace the view
FirstGroup.group.replaceView(view);

Thursday, April 28, 2011

DateTime Picker

http://blog.codeus.net/dateslider-1-0-an-alternative-datepicker-for-android/

Tuesday, April 26, 2011

URL Encode

WebView web;
public static String useragent;

web = new WebView(getApplicationContext());
useragent = Extras.URLencode(web.getSettings().getUserAgentString());


public class Extras {

public static String URLencode(String s){
if (s!=null) {
StringBuffer tmp = new StringBuffer();
int i=0;
try {
//s=java.net.URLEncoder.encode(s,"UTF-8");

while (true) {
int b = (int)s.charAt(i++);
if ((b>=0x30 && b<=0x39) || (b>=0x41 && b<=0x5A) || (b>=0x61 && b<=0x7A)) {
tmp.append((char)b);
}
else {
tmp.append("%");
if (b <= 0xf) tmp.append("0");
tmp.append(Integer.toHexString(b));
}
}

}

catch (Exception e) {
System.out.println("Error during URL Encode---"+e);
}

return tmp.toString();
}

return null;
}


public static String removecommas(String str)
{
try{
if(str.contains(","))
{
str=str.replace(",","");

return str;
}

else
return str;

}catch(Exception e){
return null;
}

}


public static String removeminus(String str)
{
try{
if(str.contains("-"))
{
str=str.replace("-","");
return str;
}
else
return str;


}catch(Exception e){
return null;
}

}
}

Friday, April 22, 2011

Thursday, April 21, 2011

Timer Thread

TimerThread timer;
Timer delay;
timer = new TimerThread();
delay = new Timer();
delay.schedule(timer,30000, 30000);

class TimerThread extends TimerTask{

@Override
public void run() {

if(flag){
doWork();
}else{
finish();
}

}
}
public void doWork() {
runOnUiThread(new Runnable() {

public void run() {
try{
write ur data-----

}
catch(Exception e)
{
System.out.println("Error-=-on thread="+e);
}
}
});
}

Wednesday, April 20, 2011

Calender

http://android.arnodenhond.com/tutorials/calendar

AR example

Data source:

package com.jwetherell.augmented_reality.data;

import java.util.List;

import com.jwetherell.augmented_reality.ui.Marker;

public abstract class DataSource{

public abstract String createRequestURL( double lat,
double lon,
double alt,
float radius,
String locale);

public abstract List parse(String url);


}

BUZZ DATA source:


package com.jwetherell.augmented_reality.data;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;

import com.jwetherell.augmented_reality.R;
import com.jwetherell.augmented_reality.parser.FeedParser;
import com.jwetherell.augmented_reality.parser.FeedParserFactory;
import com.jwetherell.augmented_reality.parser.Loc_Finder;
import com.jwetherell.augmented_reality.parser.ParserType;
import com.jwetherell.augmented_reality.parser.message;
import com.jwetherell.augmented_reality.ui.IconMarker;
import com.jwetherell.augmented_reality.ui.Marker;

public class BuzzDataSource extends DataSource {
private Logger logger = Logger.getLogger(getClass().getSimpleName());

public static int size;
private static final String BASE_URL = "http://174.129.227.226/service.htm?f=findRestaurantInAreaTakeAway";

public static List id1;

private static Bitmap icon = null;
List messages=new ArrayList();

public BuzzDataSource(Resources res) {
createIcon(res);
}

protected void createIcon(Resources res) {
icon=BitmapFactory.decodeResource(res, R.drawable.icon);
}

public Bitmap getBitmap() {
return icon;
}

public String createRequestURL(double lat, double lon, double alt, float radius, String locale) {

return BASE_URL+"&refLat="+Loc_Finder.lati+"&refLong="+Loc_Finder.longi+"&radiusInKm=10";

}

public void parseDidFinish(List messages) {
// TODO Auto-generated method stub
try{

this.messages=messages;

}
catch(Exception e){
System.out.println("Error in getting data...."+e);

}
}

public Marker updateUIwithData(String name,Double lat,Double lon){
Marker ma = null;
try {
ma = new IconMarker(
name,
lat,
lon,
0,
Color.GREEN,
icon);

} catch (Exception e) {
logger.info("Exception: "+e.getMessage());
}
return ma;
}

@Override
public List parse(String url) {

List markers=new ArrayList();

try{
FeedParserFactory f=new FeedParserFactory(url);
FeedParser parser = f.getParser(ParserType.XML_PULL);
messages=parser.parse();

List name1=new ArrayList();
List long1=new ArrayList();
List lati1=new ArrayList();
List dis1=new ArrayList();
id1=new ArrayList();
// TODO Auto-generated method stub

size=messages.size();

for (message msg : messages)
{
name1.add(msg.getname());
long1.add(msg.getlongtude());
lati1.add(msg.getlatitude());
dis1.add(msg.getdistance());
id1.add(msg.getid());
}

for(int i=0;i Marker ma=null;
ma=updateUIwithData(name1.get(i),Double.parseDouble(lati1.get(i)),Double.parseDouble(long1.get(i)));

if(ma!=null)
markers.add(ma);
}

}catch(Exception e){
System.out.println("Error in Main Load feed method");
}
return markers;

}


}
Pasrser callback:

package com.jwetherell.augmented_reality.parser;

import java.util.List;


public interface ParserCallback {

public message parseDidFinish1(List messages);
public void parseDidFinish(List messages);

}

Xml parser:


package com.jwetherell.augmented_reality.parser;

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

import org.xmlpull.v1.XmlPullParser;

import android.util.Log;
import android.util.Xml;

public class XmlPullFeedParser extends BaseFeedParser {

public XmlPullFeedParser(String feedUrl) {
super(feedUrl);
}


public List parse() {

List messages = null;
XmlPullParser parser = Xml.newPullParser();
try {
parser.setInput(getInputStream(), null);
System.out.println("Parser Data--------------\n------"+parser.getText());
int eventType = parser.getEventType();
message currentMessage = null;
boolean done = false;
while (eventType != XmlPullParser.END_DOCUMENT && !done){
String name = null;
switch (eventType){
case XmlPullParser.START_DOCUMENT:
messages = new ArrayList();
break;
case XmlPullParser.START_TAG:
name = parser.getName();
if (name.equalsIgnoreCase("restaurant")){
currentMessage = new message();
} else if (currentMessage != null){
if(name.equalsIgnoreCase("id")){
currentMessage.setid(parser.nextText());
}else if(name.equalsIgnoreCase("name")){
currentMessage.setname(parser.nextText());
}else if(name.equalsIgnoreCase("latitude")){
currentMessage.setlatitude(parser.nextText());
}else if(name.equalsIgnoreCase("longitude")){
currentMessage.setlongtude(parser.nextText());
}else if(name.equalsIgnoreCase("distance")){
currentMessage.setdistance(parser.nextText());
}else if(name.equalsIgnoreCase("cuisine")){
currentMessage.setcuisine(parser.nextText());
}
}
break;
case XmlPullParser.END_TAG:
name = parser.getName();
if (name.equalsIgnoreCase("restaurant")&& currentMessage != null){
messages.add(currentMessage);
}
else if(name.equalsIgnoreCase("dataset")){
done = true;
}
break;
}
eventType = parser.next();
}
} catch (Exception e) {
Log.e("Error Mian PullFeedParser", e.getMessage(), e);
//throw new RuntimeException(e);

}
return messages;

}


@Override
public void parse(ParserCallback messages) {
// TODO Auto-generated method stub

}

}

try this

Add Events on Google Calendar on Android

package com.ram.calender;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.widget.TextView;

public class CalenderActivity extends Activity {
TextView ret_list;
String calName;
String calId;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Date d = new Date();
d.setHours(8);
d.setMinutes(30);
d.setSeconds(30);
long startTime = d.getTime();
d.setHours(12);
d.setMinutes(35);
d.setSeconds(35);
long endtime = d.getTime();

ret_list=(TextView)findViewById(R.id.txt_retlist);

addToCalendar(this,"ramachanderan",startTime,endtime);
}


private static void addToCalendar(Context ctx, final String title, final long dtstart, final long dtend) {
final ContentResolver cr = ctx.getContentResolver();
Cursor cursor ;
if (Integer.parseInt(Build.VERSION.SDK) == 8 )
cursor = cr.query(Uri.parse("content://com.android.calendar/calendars"), new String[]{ "_id", "displayname" }, null, null, null);
else
cursor = cr.query(Uri.parse("content://calendar/calendars"), new String[]{ "_id", "displayname" }, null, null, null);
if ( cursor.moveToFirst() ) {
final String[] calNames = new String[cursor.getCount()];
final int[] calIds = new int[cursor.getCount()];
for (int i = 0; i < calNames.length; i++) {
calIds[i] = cursor.getInt(0);
calNames[i] = cursor.getString(1);
cursor.moveToNext();
}

AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setSingleChoiceItems(calNames, -1, new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
ContentValues cv = new ContentValues();
cv.put("calendar_id", calIds[which]);
cv.put("title", title);
cv.put("dtstart", dtstart );
cv.put("hasAlarm", 1);
cv.put("dtend", dtend);

Uri newEvent ;
if (Integer.parseInt(Build.VERSION.SDK) == 8 )
newEvent = cr.insert(Uri.parse("content://com.android.calendar/events"), cv);
else
newEvent = cr.insert(Uri.parse("content://com.android.calendar/events"), cv);

if (newEvent != null) {
long id = Long.parseLong( newEvent.getLastPathSegment() );
ContentValues values = new ContentValues();
values.put( "event_id", id );
values.put( "method", 1 );
values.put( "minutes", 15 ); // 15 minuti
if (Integer.parseInt(Build.VERSION.SDK) == 8 )
cr.insert( Uri.parse( "content://com.android.calendar/reminders" ), values );
else
cr.insert( Uri.parse( "content://calendar/reminders" ), values );

}
dialog.cancel();
}

});

builder.create().show();
}
cursor.close();
}

}

Tuesday, April 19, 2011

Sunday, April 17, 2011

Wednesday, April 13, 2011

SharedPreferences

SharedPreferences 1;
int 3,2;
1= this.getSharedPreferences("1",MODE_WORLD_WRITEABLE);
3=check_version.getInt("2", 0);



SharedPreferences.Editor editor=1.edit();
editor.putInt("2",3);
editor.commit();

Thursday, April 7, 2011

Android TabActivity

http://blog.lardev.com/2011/02/02/how-to-move-android-tabs-from-top-to-bottom/

Wednesday, April 6, 2011

Tab Activity


xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:gravity="bottom"
android:visibility="gone"
android:background="#000000"
>


android:id="@+id/top_tap_activity"
android:layout_height="40dip"
android:layout_width="fill_parent"
android:orientation="horizontal"
android:layout_alignParentTop="true"
>
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn_0"
android:background="@drawable/icon"
/>
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn_1"
android:background="@drawable/icon"
/>
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn_2"
android:background="@drawable/icon"
/>



android:layout_height="fill_parent"
android:layout_width="fill_parent">


Tuesday, April 5, 2011

Wednesday, March 30, 2011

Raw Data

String ReadRaw(int id)
{
try
{
InputStream raw = getResources().openRawResource(id);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
i = raw.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = raw.read();
}
raw.close();
return byteArrayOutputStream.toString();
}
catch (IOException e)
{
e.printStackTrace();
return "";
}
}

Store DB Links

http://www.screaming-penguin.com/node/7742
http://android.bigresource.com/Android-Want-Database-to-save-retrieve-names-in-phone-application-haK6YhJIr.html


main.xml


xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
"http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
android:layout_height="wrap_content"
android:text="@string/hello" />
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" />



DataHelper.java

package com.ram.sampleDB;

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

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

public class DataHelper {

private static final String DATABASE_NAME = "example.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "table1";

private Context context;
private SQLiteDatabase db;


private SQLiteStatement insertStmt;
private static final String INSERT = "insert into "
+ TABLE_NAME + "(name) values (?)";


public DataHelper(sampleDB sampleDB) {
// TODO Auto-generated constructor stub
this.context = sampleDB;
OpenHelper openHelper = new OpenHelper(this.context);
this.db = openHelper.getWritableDatabase();
this.insertStmt = this.db.compileStatement(INSERT);
}

public void deleteAll() {
// TODO Auto-generated method stub
this.db.delete(TABLE_NAME, null, null);
}

public long insert(String name) {
// TODO Auto-generated method stub
this.insertStmt.bindString(1, name);
return this.insertStmt.executeInsert();

}

public List selectAll() {
// TODO Auto-generated method stub
List list = new ArrayList();
Cursor cursor = this.db.query(TABLE_NAME, new String[] { "name" },
null, null, null, null, "name desc");
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}

private static class OpenHelper extends SQLiteOpenHelper {

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

public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY, name TEXT)");
}

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("Example", "Upgrading database, this will drop tables and recreate.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}


sampleDB.java

package com.ram.sampleDB;

import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

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

private TextView output;

private DataHelper dh;

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

this.output = (TextView) this.findViewById(R.id.out_text);

this.dh = new DataHelper(this);
this.dh.deleteAll();
this.dh.insert("Porky Pig");
this.dh.insert("Foghorn Leghorn");
this.dh.insert("Yosemite Sam");
List names = this.dh.selectAll();
StringBuilder sb = new StringBuilder();
sb.append("Names in database:\n");
for (String name : names) {
sb.append(name + "\n");
}

Log.d("EXAMPLE", "names size - " + names.size());

this.output.setText(sb.toString());

}
}

Saturday, March 19, 2011

Android Links

http://www.ndtv.com/convergence/ndtv/rssfeedback.aspx
http://www.google.com/language_tools
http://maxood-android-corner.blogspot.com/2011/03/tutorial-using-google-translate-api-in.html
http://android-er.blogspot.com/2009/10/multi-language-translate.html
http://stackoverflow.com/questions/4979078/google-translator-in-android
http://stackoverflow.com/questions/2325547/how-to-have-a-translation-service-in-android-app

Thursday, March 10, 2011

USING CANVAS TO ROTATE BALL

package in.ram.JungleMayhem;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;


public class JungleMayhem extends Activity {
//private Bitmap bg;
private DrawOval dw;
int x = 30;
int y = 230;
//private boolean start = true;
private boolean running = true;
private boolean direction = true;
private boolean direction1;
private boolean direction2;
private boolean direction3;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
//Bitmap mBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.bg1480x320);
//Bitmap bg= Bitmap.createScaledBitmap(mBitmap, 240, 320, true);
//int pic_width = mBitmap.getWidth();
//int pic_height = mBitmap.getHeight();
//ImageView img = new ImageView(this);
//img.setImageBitmap(bg);
//setContentView(img);
dw = new DrawOval(this);
setContentView(dw,new ViewGroup.LayoutParams(240,400));
(new Thread(new Animationloop())).start();
}

public void updatePhysics() {
if(direction == true) {
if(x<= 130) {
x+=1;
y-=1;
}else if(x==131){
direction = false;
direction1=true;
}
}

if(direction1==true){
if(x<=230){
x+=1;
y+=1;
}else if(x==231){
direction1=false;
direction2=true;
}
}

if(direction2==true){
if(x>=131){
x-=1;
y+=1;
}else if(x==130){
direction2=false;
direction3=true;
}
}

if(direction3==true){
if(x>=30){
x-=1;
y-=1;
}else if(x==29){
direction3=false;
direction=true;
x = 30;
y = 230;
}
}
}

class DrawOval extends View {
//Canvas c;
//private ShapeDrawable shp;
private Bitmap bg = BitmapFactory.decodeResource(getResources(),R.drawable.bg2480x320);
private Bitmap bg1= Bitmap.createScaledBitmap(bg, 240, 320, true);
private Bitmap p1 = BitmapFactory.decodeResource(getResources(),R.drawable.egg);
private Bitmap egg = Bitmap.createScaledBitmap(p1, 10, 10, true);

private Bitmap pl1 =BitmapFactory.decodeResource(getResources(),R.drawable.egg1);
private Bitmap pl2 =BitmapFactory.decodeResource(getResources(),R.drawable.egg2);
private Bitmap pl11 = Bitmap.createScaledBitmap(pl1, 45,45, true);
private Bitmap pl22 = Bitmap.createScaledBitmap(pl2, 45,45, true);


public DrawOval(Context context) {
super(context);
}
//shp = new ShapeDrawable(new OvalShape());
//shp.getPaint().setColor(0xff74AC23);
//shp.setBounds(0, 0, 480, 360);


protected synchronized void onDraw(Canvas canvas) {

canvas.drawBitmap(bg1, new Rect(0,0,240,400), new Rect(0,0,240,400), new Paint());
canvas.drawBitmap(pl11,25,150,new Paint());
canvas.drawBitmap(pl22,165,150,new Paint());
canvas.drawBitmap(egg,200,200,new Paint());
canvas.drawBitmap(egg,x,y,new Paint());
//canvas.drawBitmap(p1, new Rect(0,0,100,100), new Rect(0,0,100,100), new Paint());
//canvas.drawColor(Color.BLUE);
//shp.draw(canvas);
invalidate();
}
}

class Animationloop implements Runnable {

@Override
public void run() {
while(true) {
while(running) {
try {
Thread.sleep(10);
}catch(InterruptedException e) {
System.out.println("-------InterruptedException-----"+e);
}
//dw.postInvalidate();
updatePhysics();
}
}

}

}
}

Ondraw/canvas method

package in.ram.JungleMayhem;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;


public class JungleMayhem extends Activity {
//private Bitmap bg;
private DrawOval dw;
int x = 0;
int y = 100;
//private boolean start = true;
private boolean running = true;
private boolean direction = true;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
//Bitmap mBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.bg1480x320);
//Bitmap bg= Bitmap.createScaledBitmap(mBitmap, 240, 320, true);
//int pic_width = mBitmap.getWidth();
//int pic_height = mBitmap.getHeight();
//ImageView img = new ImageView(this);
//img.setImageBitmap(bg);
//setContentView(img);
dw = new DrawOval(this);
setContentView(dw,new ViewGroup.LayoutParams(240,320));
(new Thread(new Animationloop())).start();
}
public void updatePhysics() {
if(direction == true) {
if(x<= 80) {
x+=1;
y-=1;
}
else if(x>80 && x<=100) {
y-=0;
x+=1;
}
else if(x>=100) {
y+=1;
x+=1;
}
}
if(x==200){
direction = false;
}
if(direction == false) {
//running = false;
if(x>=100) {
x-=1;
y-=1;
}
else if(x<=100 && x>=80) {
y-=0;
x-=1;
}
else if(x<=80) {
y+=1;
x-=1;
}
if(x == 50) {
direction = true;
}

}

}

class DrawOval extends View {
//Canvas c;
//private ShapeDrawable shp;
private Bitmap bg = BitmapFactory.decodeResource(getResources(),R.drawable.bg2480x320);
private Bitmap bg1= Bitmap.createScaledBitmap(bg, 240, 320, true);
private Bitmap p1 = BitmapFactory.decodeResource(getResources(),R.drawable.egg);
private Bitmap egg = Bitmap.createScaledBitmap(p1, 10, 10, true);

private Bitmap pl1 =BitmapFactory.decodeResource(getResources(),R.drawable.egg1);
private Bitmap pl2 =BitmapFactory.decodeResource(getResources(),R.drawable.egg2);
private Bitmap pl11 = Bitmap.createScaledBitmap(pl1, 45,45, true);
private Bitmap pl22 = Bitmap.createScaledBitmap(pl2, 45,45, true);


public DrawOval(Context context) {
super(context);

//shp = new ShapeDrawable(new OvalShape());
//shp.getPaint().setColor(0xff74AC23);
//shp.setBounds(0, 0, 480, 360);
}



protected synchronized void onDraw(Canvas canvas) {

canvas.drawBitmap(bg1, new Rect(0,0,240,320), new Rect(0,0,240,320), new Paint());
canvas.drawBitmap(pl11,25,150,new Paint());
canvas.drawBitmap(pl22,165,150,new Paint());
//canvas.drawBitmap(egg,200,200,new Paint());
canvas.drawBitmap(egg,x,y,new Paint());
//canvas.drawBitmap(p1, new Rect(0,0,100,100), new Rect(0,0,100,100), new Paint());
//canvas.drawColor(Color.BLUE);
//shp.draw(canvas);
invalidate();

}
}

class Animationloop implements Runnable {

@Override
public void run() {
while(true) {
while(running) {
try {
Thread.sleep(10);
}catch(InterruptedException e) {
System.out.println("-------InterruptedException-----"+e);
}
//dw.postInvalidate();
updatePhysics();
}
}

}

}
}

Wednesday, March 9, 2011

Android Record/play

http://www.hascode.com/2010/05/sensor-fun-creating-a-simple-audio-recorderplayer/

Android Links

http://www.droidnova.com/2d-sprite-animation-in-android,471.html

http://www.deitel.com/ResourceCenters/Programming/Android/Animation/tabid/3554/Default.aspx

http://www.hascode.com/2010/05/sensor-fun-location-based-services-and-gps-for-android

/http://www.hascode.com/2010/09/playing-around-with-the-android-animation-framework/

http://developerlife.com/tutorials/?p=343

Sunday, March 6, 2011

All Type Parser

Parser:1
package com.ram.parser;

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


public class Team {


private String teamname="";
private String teamflag="";
private String innings="";

List nodeList = new ArrayList();

public String getinnings(){
return innings;
}

public String getteamname(){
return teamname;
}

public String getteamflag(){
return teamflag;
}

public void setinnings(String innings){
this.innings=innings;
}

public void setteamflag(String teamflag){
this.teamflag=teamflag;
}

public void setteamname(String teamname){
this.teamname=teamname;
}
public List getNodeList(){
return nodeList;
}

public void setNode(node node){
this.nodeList.add(node);
}



public class node{
private String name="";
private String url="";
private String image="";
private String thum="";

public void setname(String name){
this.name=name;
}
public void seturl(String url){
this.url=url;
}

public String getname(){
return name;
}
public String geturl(){
return url;
}
public void setimage(String image){
this.image=image;
}

public String getimage(){
return image;
}
public String getthum(){
return thum;
}
public void setthum(String thum){
this.thum=thum;
}
}

}


parser:1

package com.ram.parser;

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

import org.xmlpull.v1.XmlPullParser;

import com.ram.parser.Team.node;

import android.util.Log;
import android.util.Xml;

public class live_battingXMLParser extends BaseFeedParser {
ParserCallback callback;

public live_battingXMLParser(String feedUrl) {
super(feedUrl);
}


public void parse(final ParserCallback callback) {
this.callback = callback;
new Thread(){
@Override
public void run(){
boolean keepGoing = true;
while(keepGoing){
List messages = null;

XmlPullParser parser = Xml.newPullParser();
try {
parser.setInput(getInputStream(), null);
int eventType = parser.getEventType();
Team currentMessage = null;
node currentNode = null;
boolean done = false;
while (eventType != XmlPullParser.END_DOCUMENT && !done){
String name = null;
switch (eventType){
case XmlPullParser.START_DOCUMENT:
messages = new ArrayList();
break;
case XmlPullParser.START_TAG:
name = parser.getName();
if (name.equalsIgnoreCase("team")){
currentMessage = new Team();
} else if (currentMessage != null){
if (name.equalsIgnoreCase("teamname")){
currentMessage.setteamname(parser.nextText());
}else if (name.equalsIgnoreCase("inning")){
currentMessage.setinnings(parser.nextText());
}
}if (name.equalsIgnoreCase("node")){
currentNode = currentMessage.new node();
}else if (currentNode != null){
if (name.equalsIgnoreCase("name")){
currentNode.setname(parser.nextText());
}else if(name.equalsIgnoreCase("url")){
currentNode.seturl(parser.nextText());
}else if(name.equalsIgnoreCase("matchid")){
currentNode.setimage(parser.nextText());
}
}
break;
case XmlPullParser.END_TAG:
name = parser.getName();
if (name.equalsIgnoreCase("node") && currentNode != null){
currentMessage.setNode(currentNode);
}else if (name.equalsIgnoreCase("team") && currentMessage != null){
messages.add(currentMessage);
}
else if(name.equalsIgnoreCase("xml")){
done = true;
}
break;
}
eventType = parser.next();
}
} catch (Exception e) {
Log.e("Error Mian PullFeedParser", e.getMessage(), e);
//throw new RuntimeException(e);

}
//return messages;
System.out.println("Pass ctrl 2 Main");
callback.parseDidFinishLive(messages);
keepGoing = false;
}
}
}.start();
}


@Override
public List parse() {
// TODO Auto-generated method stub
return null;
}
}

paser:3

package com.ram.parser;

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

import org.xmlpull.v1.XmlPullParser;

import com.ram.parser.Team.node;

import android.util.Log;
import android.util.Xml;

public class thum_PhotoParser extends BaseFeedParser {
ParserCallback callback;

public thum_PhotoParser(String feedUrl) {
super(feedUrl);
}


public void parse(final ParserCallback callback) {
this.callback = callback;
new Thread(){
@Override
public void run(){
boolean keepGoing = true;
while(keepGoing){
List messages = null;

XmlPullParser parser = Xml.newPullParser();
try {
parser.setInput(getInputStream(), null);
System.out.println("Parser Data--------------\n------"+parser.getText());
int eventType = parser.getEventType();
Team currentMessage = null;
node currentNode = null;
boolean done = false;
while (eventType != XmlPullParser.END_DOCUMENT && !done){
String name = null;
switch (eventType){
case XmlPullParser.START_DOCUMENT:
messages = new ArrayList();
break;
case XmlPullParser.START_TAG:
name = parser.getName();
if (name.equalsIgnoreCase("flipbooks")){
currentMessage = new Team();
} else if (currentMessage != null){
if (name.equalsIgnoreCase("flipbook")){
currentMessage.setinnings(parser.getAttributeValue(0));
currentMessage.setteamname(parser.getAttributeValue(1));


}
}
{
if (name.equalsIgnoreCase("flip")){
currentNode = currentMessage.new node();
}else if (currentNode != null){
if (name.equalsIgnoreCase("caption")){
currentNode.setthum(parser.nextText());

}else if (name.equalsIgnoreCase("image")){
currentNode.setname(parser.getAttributeValue(0));
currentNode.seturl(parser.getAttributeValue(1));


}
}
}

break;
case XmlPullParser.END_TAG:
name = parser.getName();
if (name.equalsIgnoreCase("flip") && currentNode != null){
currentMessage.setNode(currentNode);
}else if (name.equalsIgnoreCase("flipbook") && currentMessage != null){
messages.add(currentMessage);
}else if(name.equalsIgnoreCase("content")){
done = true;
}
break;
}
eventType = parser.next();
}
} catch (Exception e) {
Log.e("Error Mian PullFeedParser", e.getMessage(), e);
//throw new RuntimeException(e);

}
//return messages;
System.out.println("Pass ctrl 2 Main");
callback.parseDidFinishLive(messages);
keepGoing = false;
}
}
}.start();
}


@Override
public List parse() {
// TODO Auto-generated method stub
return null;
}
}

Parser:4

package com.ram.parser;

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

import org.xmlpull.v1.XmlPullParser;

import android.util.Log;
import android.util.Xml;

public class SplashScreenXmlParser extends BaseFeedParser {
ParserCallback callback;
String[] head;

public SplashScreenXmlParser(String feedUrl) {
super(feedUrl);
}


public void parse(final ParserCallback callback) {
this.callback = callback;
new Thread(){
@Override
public void run(){
boolean keepGoing = true;
while(keepGoing){
List messages = null;
List newsMessage=null;
XmlPullParser parser = Xml.newPullParser();
try {
parser.setInput(getInputStream(), null);
System.out.println("Parser Data--------------\n------"+parser.getText());
int eventType = parser.getEventType();
head=new String[3];
splash currentMessage = null;

message currentNewsNode=null;

com.ram.parser.splash.node currentNode = null;
boolean done = false;
while (eventType != XmlPullParser.END_DOCUMENT && !done){
String name = null;
switch (eventType){
case XmlPullParser.START_DOCUMENT:
messages = new ArrayList();
newsMessage=new ArrayList();
break;
case XmlPullParser.START_TAG:
name = parser.getName();

if (name.equalsIgnoreCase("livematch_score")){
currentMessage = new splash();
} else if (currentMessage != null){
if (name.equalsIgnoreCase("teams")){
currentMessage.setteams(parser.nextText());
}else if (name.equalsIgnoreCase("status")){
currentMessage.setstatus(parser.nextText());
}else if (name.equalsIgnoreCase("clickurl")){
currentMessage.setclickurl(parser.nextText());
}else if (name.equalsIgnoreCase("smallteams")){
currentMessage.setsmallteam(parser.nextText());
}
}

if (name.equalsIgnoreCase("inng")){
currentNode = currentMessage.new node();
} else if (currentNode != null){
if (name.equalsIgnoreCase("type")){
currentNode.settype(parser.nextText());
}else if(name.equalsIgnoreCase("team")){
currentNode.setteam(parser.nextText());
}else if(name.equalsIgnoreCase("score")){
currentNode.setscore(parser.nextText());
}else if(name.equalsIgnoreCase("overs")){
currentNode.setovers(parser.nextText());
}else if(name.equalsIgnoreCase("wickets")){
currentNode.setwicket(parser.nextText());
}
}
if (name.equalsIgnoreCase("node")){
currentNewsNode = new message();
}else if (currentNewsNode != null){
if(name.equalsIgnoreCase("thumbnail")){
currentNewsNode.setthumbnail(parser.nextText());
}else if(name.equalsIgnoreCase("headline")){
currentNewsNode.setheadline(parser.nextText());
}else if(name.equalsIgnoreCase("story_id")){
currentNewsNode.setcontain_id(parser.nextText());
}
}

break;
case XmlPullParser.END_TAG:
name = parser.getName();
if (name.equalsIgnoreCase("inng") && currentMessage != null){
currentMessage.setNode(currentNode);
}else if (name.equalsIgnoreCase("livematch_score") && currentMessage != null){
messages.add(currentMessage);
}else if (name.equalsIgnoreCase("node") && currentNewsNode != null){
newsMessage.add(currentNewsNode);
}else if(name.equalsIgnoreCase("xml")){
done = true;
}
break;
}
eventType = parser.next();
}
} catch (Exception e) {
Log.e("Error Mian PullFeedParser", e.getMessage(), e);
//throw new RuntimeException(e);

}
//return messages;
System.out.println("Pass ctrl 2 Main");
callback.parseDidFinishSplesh(messages, newsMessage);
keepGoing = false;
}
}
}.start();
}


@Override
public List parse() {
// TODO Auto-generated method stub
return null;
}
}

Friday, February 25, 2011

Thursday, February 10, 2011

Android Tutorials

http://www.javacodegeeks.com/2010/09/android-reverse-geocoding-yahoo-api.html

http://www.javacodegeeks.com/search/label/Android%20Tutorial

http://www.javacodegeeks.com/2010/09/android-reverse-geocoding-yahoo-api.html

http://www.javacodegeeks.com/2010/09/android-location-based-services.html

Location Fider

LocationManager locationManager; locationManager = (LocationManager)getSystemService (Context.LOCATION_SERVICE); Location location = locationManager.getLastKnownLocation (LocationManager.GPS_PROVIDER);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,0,0,(LocationListener) this);
updateWithNewLocation(location);
}

private void updateWithNewLocation(Location location) {
TextView myLocationText = (TextView)findViewById(R.id.myLocationText);

String latLongString;

if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
} else {
latLongString = "No location found";
}

myLocationText.setText("Your Current Position is:\n" +
latLongString);
}

Tuesday, February 8, 2011

Saturday, February 5, 2011

Android-calendr

http://w2davids.wordpress.com/android-epoch-htmljavascript-calendar/

Android-ImageLoader

step:1

package com.ram.parser;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Stack;

import com.ram.CricketNext.R;



import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

public class ImageLoader {

//the simplest in-memory cache implementation. This should be replaced with something like SoftReference or BitmapOptions.inPurgeable(since 1.6)
private HashMap cache=new HashMap();

private File cacheDir;

public ImageLoader(Context context){
//Make the background thead low priority. This way it will not affect the UI performance
photoLoaderThread.setPriority(Thread.NORM_PRIORITY-1);

//Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"ram");
else
cacheDir=context.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
}

final int stub_id=R.drawable.icon;
public void DisplayImage(String url, Activity activity, ImageView imageView)
{
if(cache.containsKey(url))
imageView.setImageBitmap(cache.get(url));
else
{
queuePhoto(url, activity, imageView);
imageView.setImageResource(stub_id);
}
}

private void queuePhoto(String url, Activity activity, ImageView imageView)
{
//This ImageView may be used for other images before. So there may be some old tasks in the queue. We need to discard them.
photosQueue.Clean(imageView);
PhotoToLoad p=new PhotoToLoad(url, imageView);
synchronized(photosQueue.photosToLoad){
photosQueue.photosToLoad.push(p);
photosQueue.photosToLoad.notifyAll();
}

//start thread if it's not started yet
if(photoLoaderThread.getState()==Thread.State.NEW)
photoLoaderThread.start();
}

private Bitmap getBitmap(String url)
{
//I identify images by hashcode. Not a perfect solution, good for the demo.
String filename=String.valueOf(url.hashCode());
File f=new File(cacheDir, filename);

//from SD cache
Bitmap b = decodeFile(f);
if(b!=null)
return b;

//from web
try {
Bitmap bitmap=null;
InputStream is=new URL(url).openStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}

//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);

//Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE=120;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2 break;
width_tmp/=2;
height_tmp/=2;
scale++;
}

//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}

//Task for the queue
private class PhotoToLoad
{
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i){
url=u;
imageView=i;
}
}

PhotosQueue photosQueue=new PhotosQueue();

public void stopThread()
{
photoLoaderThread.interrupt();

}

//stores list of photos to download
class PhotosQueue
{
private Stack photosToLoad=new Stack();

//removes all instances of this ImageView
public void Clean(ImageView image)
{
for(int j=0 ;j if(photosToLoad.get(j).imageView==image)
photosToLoad.remove(j);
else
++j;
}
}
}

class PhotosLoader extends Thread {
public void run() {
// System.out.println("Thread working");
try {
while(true)
{
//thread waits until there are any images to load in the queue
if(photosQueue.photosToLoad.size()==0)
synchronized(photosQueue.photosToLoad){
photosQueue.photosToLoad.wait();
}
if(photosQueue.photosToLoad.size()!=0)
{
PhotoToLoad photoToLoad;
synchronized(photosQueue.photosToLoad){
photoToLoad=photosQueue.photosToLoad.pop();
}
Bitmap bmp=getBitmap(photoToLoad.url);
cache.put(photoToLoad.url, bmp);
if(((String)photoToLoad.imageView.getTag()).equals(photoToLoad.url)){
BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad.imageView);
Activity a=(Activity)photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
}
}
if(Thread.interrupted())
{
// System.out.println("Interrupted");
break;

}

}
}catch (InterruptedException e) {
// System.out.println("Thread Intrepted Exception "+e);
//run();
//allow thread to exit

}
catch (Exception e) {
// System.out.println("Thread error"+e);
//run();
//allow thread to exit

}
}
}

PhotosLoader photoLoaderThread=new PhotosLoader();

//Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable
{
Bitmap bitmap;
ImageView imageView;
public BitmapDisplayer(Bitmap b, ImageView i){bitmap=b;imageView=i;}
public void run()
{
if(bitmap!=null)
imageView.setImageBitmap(bitmap);
else
imageView.setImageResource(stub_id);
}
}

public void clearCache() {
//clear memory cache
cache.clear();

//clear SD cache
File[] files=cacheDir.listFiles();
for(File f:files)
f.delete();
}

}

step:2
package com.ram.parser;

import java.io.InputStream;
import java.io.OutputStream;

public class Utils {
public static void CopyStream(InputStream is, OutputStream os)
{
final int buffer_size=1024;
try
{
byte[] bytes=new byte[buffer_size];
for(;;)
{
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
}
}