Sunday, December 30, 2012

JavaScript example in Android

This is very helpful example for JavaScript

Please check
1. https://github.com/scottagarman/Android-JavaScript-Interface-Example
2. http://blog.objectgraph.com/index.php/2012/03/16/android-development-javascript-bridge-example-fully-explained/

SOURCE CODE


package ranjit.jsinandroid;
public class JSAndroid extends Activity {
private WebView wv;

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

// create interface
JsInterface jsInterface = new JsInterface();

// get webview and enable js
wv = (WebView) findViewById(R.id.web_view);
wv.getSettings().setJavaScriptEnabled(true);

// add interface
wv.addJavascriptInterface(jsInterface, "android");// android is the
// keyword that will
// be exposed in js

// load file
wv.loadUrl("file:///android_asset/test.html");
}

// javascript interface
private class JsInterface {
// function that will be called from assets/test.js
// js example: android.log('my message');
public void log(String msg) {
Log.d("MSG FROM JAVASCRIPT", msg);
Toast.makeText(getApplicationContext(), "JavaScript working...", 1)
.show();
}
}
}

---------------------
XML file


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

    <WebView
        android:id="@+id/web_view"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>

------------------
HTML file
Save test.html file in assets folder


<html> <head> </head> <body> <a href="javascript:void(0);" onclick="android.log('omg its working!');">Click on this link for a log message</a> </body> </html>


Wednesday, December 26, 2012

How to use HttpGet in Android

Source code


HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(
"http://your_webservice/username="
+ username + "/password=" + pass);
HttpResponse response = httpClient.execute(httpGet, localContext);
String responseText = EntityUtils.toString(response.getEntity());
// Log.e("HTTP Response - > ", "" + responseText);
String searchResult = parseXMLForTag(responseText,
"FinalMessageOfUserAccounts");
loginstatus = parseXMLForTag(searchResult, "Message");
Log.e("Login Status : ->", "" + loginstatus);
return loginstatus.trim();


//Using this method parse data from <xml tags>

public static String parseXMLForTag(String xml, String tag) {
try {
// Create XMLPullParserFactory & XMLPullParser
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
parser.setInput(new StringReader(xml));

// boolean to indicate desired tag has been found
boolean foundTag = false;
// variable to fill contents
StringBuilder tagContents = new StringBuilder();

// loop over document
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_TAG:
if (parser.getName().equals(tag)) {
// Found tag, start appending to tagContents
foundTag = true;
} else if (foundTag) {
// New start tag inside desired tag
tagContents.append("<" + parser.getName() + ">");
}
break;
case XmlPullParser.END_TAG:
if (parser.getName().equals(tag)) {
// Finished gathering text for tag
return tagContents.toString();
} else if (foundTag) {
// end tag inside desired tag
tagContents.append("</" + parser.getName() + ">");
}
break;
case XmlPullParser.TEXT:
if (foundTag) {
// text inside desired tag
tagContents.append(parser.getText());
}
break;
}
// Get next event type
eventType = parser.next();
}
return null;
} catch (Exception e) {
return null;
}
}

Saturday, December 22, 2012

Home Screen Counter in Android, how to find home screen is active in Android

Source Code


package ranjit.checkhomescreen;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.app.Activity;
import android.app.ActivityManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.support.v4.app.NavUtils;

public class CheckHomeScreenCounter extends Activity {
public static int counter;
public static boolean home_screen_active = false;
ActivityManager activity_manager;
TextView tv;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_home_screen_counter);
activity_manager = (ActivityManager) getSystemService(getApplicationContext().ACTIVITY_SERVICE);
tv = (TextView) findViewById(R.id.textView1);

if (counter <= 0) {
new CountDownTimer(30000, 1000) {

@Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
try {
checkLatestActi();
} catch (Exception e) {
e.printStackTrace();
Log.d("Ranjit check error", " " + e);
}
}

@Override
public void onFinish() {
// TODO Auto-generated method stub
start();
}
}.start();
}
tv.setText("Home Screen Counter:" + counter);

}

public void checkLatestActi() {
try {
if (activity_manager.getRunningTasks(Integer.MAX_VALUE).get(0).topActivity
.getPackageName().equals("com.android.launcher")) {
if (home_screen_active == true) {
home_screen_active = false;
Log.e("Got Home Screen", "In HomeScreen " + counter++);
}
} else {
home_screen_active = true;
Log.e("App Status", "Other App running...");
}
} catch (Exception e) {
Log.e("Error", "Error : " + e.getMessage());
}
}
}


Layout Xml file

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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="60dp"
        android:text="Home Screen Counter : "
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

Add permition in an Android.Menifest file

  <uses-permission android:name="android.permission.GET_TASKS" />


I hope is this helpful for you.

Please reply, comment, like if is this helpful for you......

Friday, December 21, 2012

How to set Tab Widget at bottom side in Android


Try this code for set Tab Widget at bottom side.
If you like please reply me your comments and likes.


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

    <TabHost
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@android:id/tabhost"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical" >

            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1.0" />

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="fill_parent"
                android:layout_height="70.0dip"
                android:layout_marginBottom="-4.0dip"
                android:layout_weight="0.0" />
        </LinearLayout>
    </TabHost>

</LinearLayout>


How to use Styles and Themes in Android

Thursday, December 20, 2012

How to add reference and Microsoft Office InfoPath Primary Interop Assembly in .NET


About the Microsoft Office InfoPath Primary Interop Assembly. check this link http://msdn.microsoft.com/en-us/library/office/aa943009.aspx

The following procedures describe how to set references to the Microsoft Office InfoPath primary interop and the InfoPath XML interop assemblies in a Visual Studio project.

To set a reference to the Microsoft.Office.Interop.InfoPath primary interop assembly, set a reference to Microsoft InfoPath 3.0 Type Library on the COM tab of the Add Reference dialog box. Even though you set a reference from the COM tab, a reference is established to the Microsoft.Office.Interop.InfoPath.dll primary interop assembly that is installed in the Global Assembly Cache (GAC) by the InfoPath setup program.

Set a reference to the Microsoft.Office.Interop.InfoPath primary interop assembly

  1. Open a Visual Studio managed code project.
  2. In Solution Explorer, right-click References, and then click Add Reference.
  3. On the COM tab, double-click Microsoft InfoPath 3.0 Type Library, and then click OK.
To set a reference to the Microsoft.Office.Interop.InfoPath.Xml interop assembly, browse to the Microsoft.Office.Interop.InfoPath.Xml.dll file that is installed by default in the <drive>:\Program Files\Microsoft Office\OFFICE14 folder. Even though you specify the copy of the assembly in the local file system, this procedure establishes a reference to the Microsoft.Office.Interop.InfoPath.Xml.dll assembly that is installed in the Global Assembly Cache (GAC) by the InfoPath setup program.

Set a reference to the Microsoft.Office.Interop.InfoPath.Xml interop assembly

  1. Open or create a Visual Studio managed code project, such as a Console Application or Windows Application.
  2. In Solution Explorer, right-click References, and then click Add Reference.
  3. On the .NET tab, click Browse, navigate to the <drive>:\Program Files\Microsoft Office\OFFICE14 folder, and then click Microsoft.Office.Interop.InfoPath.Xml.dll.
  4. Click OK.

How to count phone lock/unlock states in Android

Hello friends

This is simple code to count phone lock/unlock states in android

Source code


package ranjit.countlock_unlock;

import android.app.Activity;
import android.app.KeyguardManager;
import android.content.Context;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.widget.TextView;

public class Count_Lock_Unlock extends Activity {
KeyguardManager myKM;
int lock_counter = 0, unlock_counter = 0;
boolean screen_state = true;
TextView tvLock, tvUnlock;

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

tvLock = (TextView) findViewById(R.id.txtLock);
tvUnlock = (TextView) findViewById(R.id.txtUnlock);
myKM = (KeyguardManager) getApplicationContext().getSystemService(
Context.KEYGUARD_SERVICE);

new CountDownTimer(60000, 1000) {

@Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
if (myKM.inKeyguardRestrictedInputMode()) {
// it is locked
Log.e("LOCKED STATUS", "its LOCKED");
if (screen_state == true) {
lock_counter++;
tvLock.setText("LOCK : " + lock_counter);
Log.e("LOCK", "LOCK");
}
screen_state = false;
} else {
// it is not locked
Log.e("UN-LOCKED STATUS", "its UN-LOCKED");
if (screen_state == false) {
unlock_counter++;
tvUnlock.setText("UNLOCK : " + unlock_counter);
Log.e("UNLOCK", "UNLOCK");
}
screen_state = true;
}
}

@Override
public void onFinish() {
// TODO Auto-generated method stub
start();
}
}.start();
}
}


XML File


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

    <TextView
        android:id="@+id/txtLock"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="56dp"
        android:text="LOCK : "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/txtUnlock"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txtLock"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="96dp"
        android:text="UNLOCK : "
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

Sending Emails without User Intervention (no Intents) in Android

Without using Intent means without using any mailing app we can send email in background.
http://www.jondev.net/articles/Sending_Emails_without_User_Intervention_%28no_Intents%29_in_Android 


And for sending email in an simple way
http://www.mkyong.com/android/how-to-send-email-in-android/

Tuesday, December 18, 2012

How to upgrade Android app in Google Play (Android Market)

Check this link
http://developer.appcelerator.com/question/20271/publish-an-application-upgrade-on-android-market-not-work

from above link

Go to your YourApp/build/android/ folder. Make a copy of your AndroidManifest.xml. Rename it to AndroidManifest.custom.xml.
Change following lines: android:versionCode="1" android:versionName="1"
to: android:versionCode="2" // A number higher than the one above android:versionName="1.1" // Version number to show
Leave both files and recompile and zipalign. This works with me.

Saturday, December 15, 2012

OAuth and REST in Android

RESTful Web Services and Google Maps integration with Android Application

How to read all .txt (Text File) from SD Card in Android



public class FindFilesFromSDCardRanjit extends Activity {
TextView tvFileList;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_files_from_sdcard);
tvFileList = (TextView) findViewById(R.id.textViewFiles);
FindFileNames_Path("\\sdcard");
}

public void FindFileNames_Path(String dir) {

File directory = new File(dir);

if (!directory.isDirectory()) {
System.out.println("No directory provided");
return;
}

// create a FilenameFilter and override its accept-method
FilenameFilter filefilter = new FilenameFilter() {

public boolean accept(File dir, String name) {
// if the file extension is .txt return true, else false
return name.endsWith(".txt");
}
};

String[] filenames = directory.list(filefilter);

for (String name : filenames) {
System.out.println(name);
tvFileList.setText(tvFileList.getText() + "\n" + name);
}
}
}


--------------------
Main xml file
--------------------
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textViewFiles"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="List of files"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

Sunday, December 2, 2012

How to use intent in an adapter class in Android

We can easily use intent in an Adapter class.

// This is 2 line code
Intent i = new Intent(v.getContext(), DetailStores.class);
v.getContext().startActivity(i);

//Same code we can write in an single line
v.getContext().startActivity(new Intent(v.getContext(), DetailStores.class));