Tuesday, January 31, 2012

How to play flash file(in SDCard) on webView through HTML file present on sdcard ?

Create the flash.html file in sdcard which should be pointing towards flash file on sdcard......


<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html" charset="UTF-8" />
  </head>
  <body>
    <object width="215" height="140">
      <param name="movie" value="choudanse7us.swf">
        <embed src="file:///mnt/sdcard/choudanse7us.swf"
               width="215" height="140">
        </embed>
    </object>
  </body>
</html>


Create the following activity you will get the result............


public class FlashWebViewActivity extends Activity {
private WebView mWebView;

/** Called when the activity is first created. */
    @Override
    public void onCreate (Bundle savedInstanceState) {
        super. onCreate (savedInstanceState);
        setContentView(R.layout.main);



        // html file with sample swf video in sdcard

        //flash.html points to swf in sdcard

        mWebView = (WebView)findViewById(R.id.webview);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setPluginsEnabled(true);
        mWebView.getSettings().setAllowFileAccess(true);


 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            System.exit(4);
 } else {
         mWebView.loadUrl("file://" + Environment.getExternalStorageDirectory() + "/flash.html");
 }
                    }
}



How to open the flash file present on sdcard in Android Webview?

Following is the example.............Create the flash folder on sdcard and store the flash file in it and write down the following file name in String "a" variable.


public class WebViewActivity extends Activity {
Button btnprev, btnnext;
static int count;
WebView mWebView;

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

String htmlPre = "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\"></head><body style='margin:0; pading:0; background-color: black;'>";
String htmlCode =
" <embed style='width:100%; height:100%' src='http://www.platipus.nl/flvplayer/download/1.0/FLVPlayer.swf?fullscreen=true&video=@VIDEO@' " +
"  autoplay='true' " +
"  quality='high' bgcolor='#000000' " +
"  name='VideoPlayer' align='middle'" + // width='640' height='480'
"  allowScriptAccess='*' allowFullScreen='true'" +
"  type='application/x-shockwave-flash' " +
"  pluginspage='http://www.macromedia.com/go/getflashplayer' />" +
"";
String htmlPost = "</body></html>";

setContentView(R.layout.main);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginsEnabled(true);
mWebView.getSettings().setAllowFileAccess(true);

String a="Cervifert_Intro_Final.swf";
String b="file://" + Environment.getExternalStorageDirectory() + "/flash/"+a+"";


String assethtml="<object width=\"1024\" height=\"710\"> <param name=\"movie\" value=\""+b+"\"> <embed src=\""+b+"\" width=\"1024\" height=\"710\">";

String mimeType = "text/html";
String encoding = "utf-8";
if(isFlashInstalled())
mWebView.loadDataWithBaseURL("null", assethtml, mimeType, encoding, "");
else
Toast.makeText(this, "Not Present", Toast.LENGTH_LONG).show();


}
public boolean isFlashInstalled(){
 boolean flashInstalled = false;
 try {
   PackageManager pm = getPackageManager();
   ApplicationInfo ai = pm.getApplicationInfo("com.adobe.flashplayer", 0);
   if (ai != null)
     flashInstalled = true;
 } catch (NameNotFoundException e) {
   flashInstalled = false;
 }
 return flashInstalled;
 }



 @Override
 protected void onPause(){
     super.onPause();
   
     callHiddenWebViewMethod("onPause");

     mWebView.pauseTimers();
     if(isFinishing()){
     mWebView.loadUrl("about:blank");
         setContentView(new FrameLayout(this));
     }
 }

 @Override
 protected void onResume(){
     super.onResume();
     callHiddenWebViewMethod("onResume");
     mWebView.resumeTimers();
 }

 private void callHiddenWebViewMethod(String name){
 
     if( mWebView != null ){
         try {
             Method method = WebView.class.getMethod(name);
             method.invoke(mWebView);
         } catch (NoSuchMethodException e) {
             Log.e("No such method: ",  name + e);
         } catch (IllegalAccessException e) {
             Log.e("Illegal Access: ",  name + e);
         } catch (InvocationTargetException e) {
             Log.e("Invocation Target Exception: ",  name + e);
         }
     }
 }
}

How to check whether the flash is installed on android device or not?


Below method is to check flash is present or not!!!!


public boolean isFlashInstalled(){
 boolean flashInstalled = false;
 try {
   PackageManager pm = getPackageManager();
   ApplicationInfo ai = pm.getApplicationInfo("com.adobe.flashplayer", 0);
   if (ai != null)
     flashInstalled = true;
 } catch (NameNotFoundException e) {
   flashInstalled = false;
 }
 return flashInstalled;
 }



String htmlPre = "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\"></head><body style='margin:0; pading:0; background-color: black;'>";
String htmlCode = " <embed style='width:100%; height:100%' src='http://www.platipus.nl/flvplayer/download/1.0/FLVPlayer.swf?fullscreen=true&video=@VIDEO@' " +"  autoplay='true' " +"  quality='high' bgcolor='#000000' " +
"  name='VideoPlayer' align='middle'" + // width='640' height='480'
"  allowScriptAccess='*' allowFullScreen='true'" +
"  type='application/x-shockwave-flash' " +
"  pluginspage='http://www.macromedia.com/go/getflashplayer' />" +
"";
String htmlPost = "</body></html>";



if(isFlashInstalled()){
                 //Load the flash content if not found it will open the installation site
mWebView.loadDataWithBaseURL("null", htmlPre+htmlCode+htmlPost, "text/html", "UTF-8", "");
}
else{
                //Not present
}

Monday, January 30, 2012

Loading a image from sdcard in different ways?



Android - Load a image in a file (not drawable) as image in the layout

Sometimes, it is easier load a image from other directory (sdcard, for example) 
than load a image from drawable because for this last case, the image should be
 stored in the directory res/drawable first and packaged along with the apk files.

To load a image from a directory, it should be converted to the drawable first. 
Here comes a piece of code which can help:

File file = new File ("/sdcard/1.jpg");
ImageView imageView = (ImageView) findViewById(R.id.icon);
imageView.setImageDrawable(Drawable.createFromPath(file.getAbsolutePath()));

Be warning that there is another method for ImageView called setImageURI(URI uri).
 This method is used to load external files, it doesn't work with the type file.
 For example, this code won't work:


File file = new File ("/sdcard/1.jpg");
ImageView imageView = (ImageView) findViewById(R.id.icon);
imageView.setImageURI(Uri.fromFile(file));
--------------------------------------------------------------------------------------------------------------------------------
The another way to use image from sdcard you can write the following code...........


imagePath="/sdcard"+"/"+filename;
try {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
imageview.setImageBitmap(bitmap);

} catch (Exception e) {
e.printStackTrace();
File photos= new File("/sdcard/", "/Wockhardt/"+selectedFolderName+"/"+filename);
Bitmap b = decodeFile(photos);
imageview.setImageBitmap(b);



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=70;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    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;
    }

Animate the layout's towards right and left i.e moving towards inside?

Create the  file reverse_left.xml


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

    <translate
        android:duration="1000"
        android:fromXDelta="-100%p"
        android:toXDelta="0" />

    <alpha
        android:duration="1000"
        android:fromAlpha="1.0"
        android:toAlpha="1.0" />

</set>

and reverse_right.xml


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

    <translate
        android:duration="1000"
        android:fromXDelta="100%p"
        android:toXDelta="0" />

    <alpha
        android:duration="1000"
        android:fromAlpha="1.0"
        android:toAlpha="1.0" />

</set>


And just use it for your imageview and layout.....


img = (ImageView) findViewById(R.id.imageView1);
layout = (LinearLayout) findViewById(R.id.lin);



Animation rightAnimation = AnimationUtils.loadAnimation(this, R.anim.reverse_right);
Animation leftAnimation = AnimationUtils.loadAnimation(this, R.anim.reverse_left);

img.startAnimation(rightAnimation);
layout.startAnimation(leftAnimation);


How to write and read xml file on sdcard?


public static void WriteFile(String filenames,String content)
{
File file = new File("/sdcard/", filenames);
if (file.exists() || (!file.exists())) {
            FileOutputStream fos = null;
try {
fos = new FileOutputStream(file, false);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
            try {
fos.write(content.getBytes());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
         
}
}

public static String ReadFile(String filenames)
{
String content = null;

File myFile = new File("/sdcard/", filenames);
if (myFile.exists()) {
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(myFile);
}
catch (FileNotFoundException e2) {
return content;
}
try {
BufferedReader readerRead1 = new BufferedReader(new InputStreamReader(inputStream));
content = readerRead1.readLine();
} catch (IOException e1) {
// TODO Auto-generated catch block
return content;
}

}
return content;
}

How to read Read Asset file?


public static String ReadFromAssetFile(Context context,String filenames)
{
String content = "";

InputStream inputStream = null;
try {
inputStream = context.getAssets().open(filenames);
BufferedReader readerRead1 = new BufferedReader(new InputStreamReader(inputStream));
String line="";
while((line=readerRead1.readLine())!=null){
content+=line.trim();
}
} catch (IOException e1) {
// TODO Auto-generated catch block
return content;
}


return content;
}

Create custom spinner and other working's?



private ArrayAdapter<String> monthadapter = new ArrayAdapter<String>(this,R.layout.spinner, SalesPlannerArrayList.monthYearAray);
monthadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn_monthList.setAdapter(monthadapter);
monthadapter.notifyDataSetChanged();


int setPostion=SalesPlannerArrayList.monthIdArray.indexOf(intentMonthId);
spn_monthList.setSelection(setPostion);


Create spinner.xml in layout folder and write down the following........


<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
style="?android:attr/spinnerItemStyle"
    android:singleLine="true"
    android:textSize="14sp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ellipsize="marquee" />



Changing the font in spinner ------------->

ccrAdapter = new ArrayAdapter<String>(this,R.layout.spinner,combineArray)
{
@Override
public View getView(int position, View convertView,ViewGroup parent) {
View view=super.getView(position, convertView, parent);
TextView chk=(TextView) view.findViewById(android.R.id.text1);
chk.setTypeface(font1);
return view;
}

 };
 ccrAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
 spnChemist.setAdapter(ccrAdapter);
 ccrAdapter.notifyDataSetChanged();






How to make method to wait before returning the value?


try {
Thread.currentThread().sleep(4000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

How to send request through SOAP?

Just put the Soap.jar file in the lib folder of your application..........

public static String getResponse(String namespace, String url, String soapAction, String methodName, String requestString,Context context) {
String response = null;

SoapObject request = new SoapObject(namespace, methodName);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
  //you can add multiple parameters with the help of addProperty
request.addProperty("xmlString", requestString);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(url);
androidHttpTransport.debug = true;

try {
Log.e("Sending Request", requestString);
androidHttpTransport.call(soapAction, envelope);
Object soapResponse = envelope.getResponse();


if(soapResponse!=null){
response = soapResponse.toString();}
else{
response="";}

Log.e("Getting Response", response);

} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}

return response;
}

How to set the typeface of a layout at a time?



ViewGroup rootVIew = (ViewGroup) findViewById(R.id.activity_planner_rootlayout);
font1 = Typeface.createFromAsset(getAssets(), "MyriadPro-Cond.ttf");



public static void setTypeFaceForChilds(ViewGroup viewGroup,Typeface typeface) {
final int childCount = viewGroup.getChildCount();

for (int i = 0; i < childCount; i++) {
View view = viewGroup.getChildAt(i);

if (view instanceof ViewGroup) {
setTypeFaceForChilds((ViewGroup) view,typeface);
} else if(view instanceof TextView){
((TextView) view).setTypeface(typeface);
}

}
}




How to use Telephony of android device?



For Checking the Internet connection either WIFI or DataConnection---------->


public static boolean checkConnection(Context c)
{
ConnectivityManager mConnectivityManager = (ConnectivityManager) c
.getSystemService(Context.CONNECTIVITY_SERVICE);
TelephonyManager telephonyManager = (TelephonyManager) c
.getSystemService(Context.TELEPHONY_SERVICE);

if (mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.isConnected() || telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED)
return true;
else
return false;
//  return true;
}


For retrieving IMEI or MACAddress----------->


public String getDevice_ID() {

IMEI_NO = ((TelephonyManager) getSystemService(TELEPHONY_SERVICE))
.getDeviceId();

if (IMEI_NO == null || IMEI_NO == "358673013795895") {
Log.d(TAG, "IMEI is null");
IMEI_NO = ((WifiManager) (getSystemService(WIFI_SERVICE)))
.getConnectionInfo().getMacAddress();
Log.d(TAG, "Mac address is:" + IMEI_NO);

}






Working with Date and Time?

For getting current time ------->

public static String getCurrentTimeStamp() {
   SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");//dd/MM/yyyy
   Date now = new Date();
   String strDate = sdfDate.format(now);
   return strDate;
}


For Comparing time---------->

public static boolean TimeComperator(String time1,String time2) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("H:mm"); 
        Date pastDate=(Date) formatter.parse(time1); 
        Date futureDate=(Date)formatter.parse(time2); 
            if(pastDate.before(futureDate)) 
            {
            return true;
            }
            return false;
    }


For comparing date--------->

 public static boolean dateComparator(String date1, String date2)throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date pastDate = (Date) formatter.parse(date1);
Date futureDate = (Date) formatter.parse(date2);
if (pastDate.before(futureDate)||pastDate.equals(futureDate)) {
return true;
}
return false;
}




For email validation---------->



private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; 

    public static boolean EmailValidator(String email) { 
    pattern = Pattern.compile(EMAIL_PATTERN);
    Matcher matcher = pattern.matcher(email); 
    return matcher.matches();
    } 






How to change the default transition between activities?



In android the default transition between activities is to slide from left to right.But with custom animations we can change that.First create a folder inside the res/drawable folder called “anim”.Then create a file named “fade.xml” and copy this code into it.
<?xml version="1.0" encoding="utf-8"?>

     android:interpolator="@android:anim/accelerate_interpolator"

      android:fromAlpha="0.0" android:toAlpha="1.0"

       android:duration="@android:integer/config_longAnimTime" />
create another file named “hold.xml” in the same place hold.xml.

<?xml version="1.0" encoding="utf-8"?>

<translate xmlns:android="http://schemas.android.com/apk/res/android"

       android:interpolator="@android:anim/accelerate_interpolator"

       android:fromXDelta="0" android:toXDelta="0"
 android:duration="@andro id:integer/config_longAnimTime" />
and just before starting the activity write down the following code
startActivity(new Intent(ActivityAnimation.this, SecondClass.class));
overridePendingTransition(R.anim.fade.xml,R.anim.hold.xml);