Live Folder Example : Getting Saved Contacts to livefolder

Following Example Demonstrates how to create Live Folder and getting contacts to this live foler.

Live Folder is useful in many ways you can bring live RSSFeed and any Builtin / custom content provider
data to live folder

activity_main.xml

<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"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

</RelativeLayout>

LiveFolderActivity.java

package com.example.livefolder;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.provider.ContactsContract;
import android.provider.LiveFolders;
import android.view.Menu;

public class MainActivity extends Activity {

	//public static final Uri CONTENT_URI = Uri.parse("content://contacts/");
	public static final Uri CONTENT_URI = People.CONTENT_URI;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final Intent intent = getIntent();
        final String action = intent.getAction();

        if (LiveFolders.ACTION_CREATE_LIVE_FOLDER.equals(action)) {
            setResult(RESULT_OK, createLiveFolder(getApplicationContext(), CONTENT_URI,
                    "Contacts", R.drawable.ic_launcher));
        } else {
            setResult(RESULT_CANCELED);
        }

        finish();
    }

    private static Intent createLiveFolder(Context context, Uri uri, String name, int icon) {
        final Intent intent = new Intent();

        intent.setData(uri);
        intent.putExtra(LiveFolders.EXTRA_LIVE_FOLDER_NAME, name);
        intent.putExtra(LiveFolders.EXTRA_LIVE_FOLDER_ICON,
                Intent.ShortcutIconResource.fromContext(context, icon));
        intent.putExtra(LiveFolders.EXTRA_LIVE_FOLDER_DISPLAY_MODE, LiveFolders.DISPLAY_MODE_LIST);

        return intent;
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
}

AndroidManifest.xml file

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="8" />
    <uses-permission android:name="android.permission.READ_CONTACTS"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.livefolder.MainActivity"
            android:label="@string/app_name" >
                <intent-filter>
             <action android:name="android.intent.action.CREATE_LIVE_FOLDER"/>
             <category android:name="android.intent.category.DEFAULT" />
       </intent-filter>
            
                    </activity>
    </application>

</manifest>

LiveFolder1

LiveFolder2

LiveFolder3

LiveFolder4

Insert, Update and Delete Contact Using ContentProvider

Following Code demonstrates insert, update and delete contact using Content provider

activity_main.xml

<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"
    tools:context=".MainActivity" >
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/imageView1"
        android:layout_toLeftOf="@+id/imageView1"
        android:text="Button" />

</RelativeLayout>

ContactIUD.java

package com.example.contactscp5a;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

	Cursor c;
	int count=0;
	Uri u,pu;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		createContact("mca5a","1111");
		
		Button b = (Button)findViewById(R.id.button1);
		b.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
                                  createContact("ASDFG");
				//deleteContact("ASDFG");
				//updateContact("pqr");
			}
		});
		
	}
	private void updateContact(String nm)
	{
		ContentValues cv = new ContentValues();
		//cv.put(People.NAME, "mca5a");
		cv.put(People.Phones.TYPE, People.TYPE_HOME);
		cv.put(People.NUMBER, "89898");
	//	Cursor c = managedQuery(People.CONTENT_URI, new String[]{People.NAME}, People.NAME+"=?", new String[]{nm}, null);
		//Toast.makeText(getApplicationContext(), c.getCount()+"", 50).show();
		getContentResolver().update(pu, cv, 
				null,null);
	}
	private void createContact(String nm,String phno)
	{
		ContentValues cv = new ContentValues();
		cv.put(People.NAME, nm);
		u = getContentResolver().insert(People.CONTENT_URI, cv);
		pu = Uri.withAppendedPath(u, People.Phones.CONTENT_DIRECTORY);
		cv.clear();
		cv.put(People.Phones.TYPE, People.TYPE_MOBILE);
		cv.put(People.NUMBER,phno);
		u = getContentResolver().insert(pu, cv);
	}
	private void deleteContact(String nm)
	{
		getContentResolver().delete(People.CONTENT_URI, 
				People.NAME+"=?", new String[]{nm});
		////getContentResolver().delete(u, null, null);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}

Parsing XML File stored in raw folder using XPath

Following code demonstrates how to parse XML file stored in res/raw folder using XPath

Save following file in res – raw folder as data.xml

<?xml version="1.0" encoding="UTF-8"?>
<sample>
    <info>
        <title>Using XPath to parse XML</title>
        <author>Pete Houston</author>
    <list>
        <person id="1">
            <name>abc</name>
            <age>22</age>
        </person>
 
        <person id="2">
            <name>def</name>
            <age>27</age>
        </person>
 
        <person id="3">
            <name>ghi</name>
            <age>22</age>
        </person>
    </list>
    </info>
</sample>

XMLParse.java

package com.example.xmlparsing;

import java.util.ArrayList;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Toast;

public class MainActivity extends ListActivity {

	ArrayList<String> mPeople = new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            parseData();
        } catch(Exception ex) {
            Toast.makeText(this, "Exception: " + ex.getMessage(), Toast.LENGTH_LONG).show();
        }
 
        // pass adapter w/ data queried through XPath to ListView
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mPeople);
        setListAdapter(adapter);
    }
    private void parseData() throws Exception {
        // create an InputSource object from /res/raw
        InputSource inputSrc = new InputSource(getResources().openRawResource(R.raw.data));
        // query XPath instance, this is the parser
        XPath xpath = XPathFactory.newInstance().newXPath();
        // specify the xpath expression
        String expression = "//name";
        // list of nodes queried
        NodeList nodes = (NodeList)xpath.evaluate(expression, inputSrc, XPathConstants.NODESET);
 
        //Toast.makeText(this, "count: " + String.valueOf(nodes.getLength()),Toast.LENGTH_SHORT).show();
        // if node found
        if(nodes != null && nodes.getLength() > 0) {
            mPeople.clear();
            int len = nodes.getLength();
            for(int i = 0; i < len; ++i) {
                // query value
                Node node = nodes.item(i);
                mPeople.add(node.getTextContent());
            }
        }
    }
    
}

XMLParsing1

Testing Network ( Wifi and Mobile) Connection

Following code tests whether network is available and/or connected?

package com.example.networkapidemo5b;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		try
		{
			ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			String s = "Available : " + ni.isAvailable() + "Connected : " + ni.isConnected();
			Toast.makeText(getApplicationContext(), s, 100).show();

                        ni = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
			s = "Available : " + ni.isAvailable() + "Connected : " + ni.isConnected();
			Toast.makeText(getApplicationContext(), s, 100).show();

		}	
		catch(Exception e)
		{
			Toast.makeText(getApplicationContext(), e.getMessage(), 50).show();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}

File Read – Write Example

Following Code demonstrates how to read data from file and write data to file.

layout – activity_main.xml

<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"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="68dp"
        android:layout_marginTop="40dp"
        android:ems="10"
        android:inputType="textMultiLine" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="45dp"
        android:text="Button" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_centerVertical="true"
        android:text="Button" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/button2"
        android:layout_below="@+id/button2"
        android:layout_marginTop="58dp"
        android:text="TextView" />

</RelativeLayout>

FileReadWrite.java

package com.example.filereadwrite5a;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Button bwrite = (Button)findViewById(R.id.button1);
		Button bread = (Button)findViewById(R.id.button2);
		final EditText ed = (EditText)findViewById(R.id.editText1);
		final TextView tv = (TextView)findViewById(R.id.textView1);
//		
//		
		bwrite.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				File f = getCacheDir();
				File newfile = new File(f,"mca5.abc");
				try
				{
				newfile.createNewFile();
				//newfile.
				FileOutputStream fos = new FileOutputStream(newfile.getAbsolutePath());
				fos.write(ed.getText().toString().getBytes());
				fos.close();
				}
				catch(Exception e)
				{}
//				File f = getFilesDir();
//				String filelist[] = f.list();
//				String s;
//				for (int i=0;i<filelist.length;i++)
//				{
//					Toast.makeText(getApplicationContext(),filelist[i], 50).show();
//				}
//				try 
//				{
//					String s = ed.getText().toString();
//					FileOutputStream fos = openFileOutput("test.txt", MODE_APPEND);
//					fos.write(s.getBytes());
//					fos.close();
//				} 
//				catch (Exception e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
				
			}
		});
		bread.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try 
				{
					FileInputStream fis = openFileInput("mca5a.txt");
					DataInputStream dis = new DataInputStream(fis);
					String s="";
					String s1 = "";
					while ((s=dis.readLine())!=null)
					{
						s1 += s;
					}
					tv.setText(s1.toString());
				} 
				catch (Exception e) 
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		});
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}

AsyncTask Class Example

There are two ways to offload main thread’s task
1) Java Thread Class
2) AsyncTask class

Following Code demonstrates how to use AsyncTask class to offload task of main thread.

activity_main.xml

<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"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="48dp"
        android:layout_toLeftOf="@+id/textView1"
        android:text="Button" />

</RelativeLayout>

AsyncTaskActivity.java

package com.example.asynctaskactivity;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements View.OnClickListener 
{
	Button btn;
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		btn = (Button) findViewById(R.id.button1);
	
		//because we implement OnClickListener we only have to pass "this" (much easier)
		btn.setOnClickListener(this);
	}

	public void onClick(View view)
	{

		switch(view.getId())
		{
			case R.id.button1:
//				for(int i=0;i&lt;5;i++) {
//					try {
//						Thread.sleep(1000);
//					} catch (InterruptedException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
//				}
//				TextView txt = (TextView) findViewById(R.id.textView1);
//				txt.setText(&quot;Executed&quot;);
				new LongOperation().execute(&quot;&quot;);
				break;
		}	

	}
	private class LongOperation extends AsyncTask {

		@Override
		protected String doInBackground(String... params) {
			Log.d("xml", "DoinBackground");
			for(int i=0;i&lt;5;i++) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			return &quot;Executed&quot;;
		}      

		@Override
		protected void onPostExecute(String result) 
		{
			Log.d(&quot;xml&quot;, &quot;OnPostExecute&quot;);
			TextView txt = (TextView) findViewById(R.id.textView1);
			txt.setText(&quot;Executed&quot;); // txt.setText(result);
			//might want to change &quot;executed&quot; for the returned string passed into onPostExecute() but that is upto you
		}

		@Override
		protected void onPreExecute() 
		{
			Log.d(&quot;xml&quot;, &quot;OnPreExecute&quot;);
		}

		@Override
		protected void onProgressUpdate(Void... values) {
		}
	}
}

Web – API Demo

Following Code Demonstrates How to Display HTML page stored in Asset folder to display in webview
test.html file contains HTML + JavaScript code
test1.html is an example where Android Source code is communicating with Javascript code Stored in Assets folder
and viceversa.

Assets – test.html

<html>
	<title>WEB-API Demo</title>
	<script language="JavaScript">
		function f1()
		{
			alert("hello");
		}
	</script>
	<body>
		<form>
			<input type="button" value="hello" onClick="f1()"/>
		</form>
	</body>
</html>

Assets -> test1.html

<html>
<head>
<script type="text/javascript">
function doAlert() 
{
	alert("This is an alert.");
}
function doToast()
{
	mca5a.testtoast(document.getElementById("form_text").value,50);
}
function doLog()
{
	console.log("this is test log");
}
function doSetHTMLText(update)
{
	document.getElementById("form_text") = update;
}
</script>
</head>
<body>
<h2>This is a test.</h2>
<input type="text" value="data" id="form_text"/>
<input type="button" value="Alert" onclick="doAlert();" />
<input type="button" value="Toast" onclick="doToast();" />
<input type="button" value="Log" onclick="doLog();" />
</body>
</html>

WebAPIDEmo.java

package com.example.webapidemo5a;



import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebSettings.TextSize;
import android.webkit.WebSettings.ZoomDensity;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		final WebView wv = (WebView)findViewById(R.id.wv1);
		//final TextView tv = (TextView)findViewById(R.id.textView1);
		wv.getSettings().setJavaScriptEnabled(true);
		wv.setWebChromeClient(new WebChromeClient());
		wv.addJavascriptInterface(new test(), "mca5a");
//		wv.loadUrl("file:///android_asset/test.html");
		wv.loadUrl("file:///android_asset/test1.html");
		
	}
	public void setHTMLText(View view) 
	{
		WebView wv = (WebView) findViewById(R.id.wv1);
		wv.loadUrl("javascript:doSetHTMLText('Java->JS call');");
	}
	public class test
	{
		public void testtoast(String msg,int duration)
		{
			Toast.makeText(getApplicationContext(), msg, duration).show();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}