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