Skip to main content

Posts

Showing posts from March, 2013

Restrict Edittext input content using Input Filters in ANDROID

InputFilter filter = new InputFilter() { public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { // TODO Auto-generated method stub for (int i = start; i < end; i++) { if (Character.isLetter(source.charAt(i))) { System.out.println("Input consist of only characters from 'a' to 'z'"); return ""; } } return null; } }; edit.setFilters(new InputFilter[]{filter}); Here the filters will check whether the input content has only characters from 'a' to 'z'. same way use the condition below to have characters from'a' to 'z' and '0' to '9' and avoid special characters. Character.isLetterOrDigit(source.charAt(i))

Simple AutoComplete TextView in ANDROID

public class Autocomplete extends Activity { String name[]={ "John", "Angel", "Mark", "Angelina", "Jhony", "Juli", "Augustine", "Robert", "Reena", "Ancilina", "Mary", "Juliet" }; AutoCompleteTextView autotextview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_autocomplete); autotextview=(AutoCompleteTextView) findViewById(R.id.myautocomplete); autotextview.setAdapter(new ArrayAdapter<string>(this, android.R.layout.simple_dropdown_item_1line, name)); }

View Flipper with Animationin ANDROID

Suppose you have to show an item for few minutes and then flips to next one we can use viewflipper . ViewFlipper inherits from frame layout, so it displays a single view at a time. in java class: ViewFlipper vflip; vflip=(ViewFlipper) findViewById(R.id.viewFlipper1); //when a view is displayed vflip.setInAnimation(this,android.R.anim.fade_in); //when a view disappears vflip.setOutAnimation(this, android.R.anim.fade_out); vflip.setFlipInterval(500); vflip.startFlipping();//starts flippin // vflip.stopFlipping();//stops flipping in 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" > <ViewFlipper android:id="@+id/viewFlipper1" android:layout_width="wrap_content" android:l

Latest Chrome Beta for Android reduces data usage by half

The last time we reported about Chrome Beta for Android we were excited to show how Google’s popular browser can be modified to render pages in full-screen mode. This time, users with heavy mobile data usage are in for a treat: Chrome 26 Beta adds a new experimental feature that makes use of Google’s proxy servers to optimize web content, thereby saving bandwidth. The reduction in data usage is made possible by Google’s utilization of its own proxy servers, which phones running Chrome mobile establish a connection with and transmit HTTP requests. The proxy servers then pass on the request to the target resource, performs content optimization, and finally sends back a lighter load to the phones. read more: http://www.androidauthority.com/latest-chrome-beta-android-reduces-data-usage-half-165262/

BlackBerry plans security feature for Android, iPhone

BlackBerry will offer technology to separate and make secure both work and personal data on mobile devices powered by Google Inc's Android platform and by Apple Inc's iOS operating system, the company said on Thursday. The new feature could help BlackBerry sell high-margin services to enterprise clients even if many, or all, of their workers are using smartphones made by BlackBerry's competitors. That may be crucial for the company as it has lost a vast amount of market share to the iPhone and to Android devices, such as Samsung Electronics Co's Galaxy line. Jefferies analyst Peter Misek said he expects BlackBerry's device management software to gain traction this year, and boost revenue next year. read more: http://www.financialexpress.com/news/blackberry-plans-security-feature-for-android-iphone/1088255

Open wifi settings in android

final Intent intent = new Intent(Intent.ACTION_MAIN, null); intent.addCategory(Intent.CATEGORY_LAUNCHER); final ComponentName cn = new ComponentName("com.android.settings","com.android.settings.wifi.WifiSettings"); intent.setComponent(cn); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity( intent); 

Check different Network status in Android

public class CheckConnectionsDemo extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); checkAvailableConnection(); } void checkAvailableConnection() { ConnectivityManager connMgr = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE); final android.net.NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); final android.net.NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if( wifi.isAvailable() ) { Toast.makeText(this, "Wifi Available" ,Toast.LENGTH_LONG).show(); } else if( mobile.isAvailable() ) { Toast.makeText(this, "3G Available" ,Toast.LENGTH_LONG).show(); } else{ Toast.makeText(this, "No Network Available" ,Toast.LENGTH_LONG).show(); } } }

Programatically enable or disable WIFI in android

simple code snippet to enable WI-FI in android programatically in android. public boolean enableWIFI() { WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); if(wifiManager.isWifiEnabled()) { if(wifiManager.setWifiEnabled(false)) return true; } else { if(wifiManager.setWifiEnabled(true)) return true; } return false; } Make sure that you add the permissions: <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE">

Using external font in ANDROID

TextView text =(TextView) findViewById(R.id.textview); Typeface face; face = Typeface.createFromAsset(getAssets(), "AMAZB.TTF"); text.setTypeface(face); text.setTextSize(30); text.setTextColor(Color.WHITE);

Inflate an xml in ANDROID

RelativeLayout mainLayout = (RelativeLayout)findViewById(R.id.relative); //create a view to inflate the layout_item ( the xml with the textView created before) View view = getLayoutInflater().inflate(R.layout.inflate,mainLayout,false); //add the view to the main layout mainLayout.addView(view);                          

SQLiteManager plugin for Eclipse

See more basics on Android along with interview questions How can we access the database?i will give solution to all these problems. I created the database from my previous post about Using SQLite in ANDROID You can see the sqlite database in eclipse by opening File Explorer .Then /data/data/package_name/databases But here we cannot see the tables and table data . For viewing the table details Eclipse has a plugin. You can download the jar from below.           download jar Now put the jar in the folder eclipse/dropins/ and restart the eclipse and now you can see the sqlitemanager plugin on the top right of the File Explorer window reference link : http://www.coderzheaven.com/2011/04/18/sqlitemanager-plugin-for-eclipse/

A complete reference to Database Helper Class in SQLite in ANDROID

For COMPLETE TUTORIALS see here : DABASEHELPER CLASS : 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; public class DBAdapter { public static final String KEY_ROWID = "id"; public static final String KEY_NAME = "title"; public static final String KEY_NICKNAME = "duedate"; private static final String DATABASE_NAME = "assinDB.db"; private static final String DATABASE_TABLE = "assignments"; private static final int DATABASE_VERSION = 2; private final Context context; private DatabaseHelper ObjectDBHelper; private SQLiteDatabase db; public DBAdapter(Context ctx) { context = ctx; } private static class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context con

Get a single record from SQLite in ANDROID

For COMPLETE TUTORIALS see here : in DATABASE HELPER class: String[] coloumns = new String[] { KEY_ROWID, KEY_NAME, KEY_NICKNAME }; // calling elements in an array Cursor c = db.query(DATABASE_TABLE, coloumns, KEY_ROWID + "=" + l,null, null, null, null); if (c != null) { c.moveToFirst(); String name = c.getString(1); // since name is in position 1 ie second coloumn return name; } return null; in sqlite.java : String s =editinfo.getText().toString(); long l=Long.parseLong(s); DBAdapter adapter=new DBAdapter(SQliteExample.this); adapter.open(); String returnedname=adapter.returnName(l); String returnednickname=adapter.returnickname(l); adapter.close(); editName.setText(returnedname); editNickName.setText(returnednickname);

Get all records from SQLite in ANDROID

For COMPLETE TUTORIALS see here : in DABASEHELPER CLASS : String[] coloumns = new String[] { KEY_ROWID, KEY_NAME,KEY_NICKNAME }; // calling all elements in an array Cursor c = db.query(DATABASE_TABLE, coloumns, null, null, null, null,null);// basically reading a database need cursor String result = " ";// since string is to be returned System.out.println("count of cursor=====>>" + c.getCount()); int iRowid = c.getColumnIndex(KEY_ROWID); // calling each row values int iRowName = c.getColumnIndex(KEY_NAME); int iRowNickName = c.getColumnIndex(KEY_NICKNAME); if (c.moveToFirst()) { c.moveToFirst(); for (int i = 0; i < c.getCount(); i++) {result = result + c.getString(iRowid) + " " + c.getString(iRowName) + " " + c.getString(iRowNickName) + "\n"; System.out.println(result + " <> " + i

Modify records in SQLite in ANDROID

For COMPLETE TUTORIALS see here : in DABASEHELPER CLASS : ContentValues cvupdate = new ContentValues(); // Bundle for writting the database fields cvupdate.put(KEY_NAME, namestr);// put the values passed to ContentValues cvupdate.put(KEY_NICKNAME, nickstr);// put the values passed to ContentValues db.update(DATABASE_TABLE, cvupdate, KEY_ROWID + "=" + smodify, null);// specify where to be changed in sqlite.java : String Namestr = editName.getText().toString(); String Nickstr = editNickName.getText().toString(); String smodify =editinfo.getText().toString(); long lmodify =Long.parseLong(smodify); DBAdapter adaptmodify =new DBAdapter(SQliteExample.this); adaptmodify.open(); adaptmodify.updateentry(lmodify,Namestr,Nickstr); // pass index and new values to be inserted adaptmodify.close();

Delete records from SQLite table in ANDROID

For COMPLETE TUTORIALS see here : in DABASEHELPER CLASS : public void deleteentry(long ldelete) { // TODO Auto-generated method stub db.delete(DATABASE_TABLE, KEY_ROWID + "=" +ldelete, null); } in Sqlite.java : String sdelete =editinfo.getText().toString(); long ldelete =Long.parseLong(sdelete); DBAdapter adaptdelete =new DBAdapter(SQliteExample.this); adaptdelete.open(); adaptdelete.deleteentry(ldelete); //pass the index to be deleted adaptdelete.close();

Insert records in SQLite tables in ANDROID

For COMPLETE TUTORIAL see here : in DABASEHELPER CLASS : public void entryfield(String namestr, String nickstr) { ContentValues cv = new ContentValues(); // Bundle for writting the database fields cv.put(KEY_NAME, namestr);// put the values passed to ContentValues cv.put(KEY_NICKNAME, nickstr);// put the values passed to ContentValues db.insert(DATABASE_TABLE, null, cv);// insert into databse with vlues as "content vales" } in sqlite.java //==Create an object of adapter class to call methods== DBAdapter Entryadapter = new DBAdapter(SQliteExample.this); Entryadapter.open(); Entryadapter.entryfield(Namestr,Nickstr); // Calling the function in DBAdapter Class Entryadapter.close();

Simple SQLite Example in Android

See more basics on Android along with interview questions DBAdapter.java (DABASEHELPER CLASS) 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; public class DBAdapter { public static final String KEY_ROWID = "id"; public static final String KEY_NAME = "title"; public static final String KEY_NICKNAME = "duedate"; private static final String DATABASE_NAME = "assinDB.db"; private static final String DATABASE_TABLE = "assignments"; private static final int DATABASE_VERSION = 2; private final Context context; private DatabaseHelper ObjectDBHelper; private SQLiteDatabase db; public DBAdapter(Context ctx) { context = ctx; } private static class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context

TextView with link in ANDROID…….

in java class: import android.app.Activity; import android.os.Bundle; import android.text.Html; import android.text.method.LinkMovementMethod; import android.widget.TextView; public class TextViewLinkDemo extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView tv = (TextView) findViewById(R.id.tv); tv.setText( Html.fromHtml(" This is a textView with a link " +" AngelMark Blog " + "created in the Java source code using HTML.")); tv.setMovementMethod(LinkMovementMethod.getInstance()); } } main.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width=&q

Parsing an XML from Online in Android

Create a fresh project and name it ParseXMLDemo Then in the ParseXMLDemo.java file copy this code | import java.util.ArrayList; import java.util.HashMap; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import android.app.ListActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; public class ParseXMLDemo extends ListActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ArrayList<String> mylist = new ArrayList<String>(); String xml = ParseXMLMethods.getXML(); Document doc = ParseXMLMethods.XMLfromString(xml); int numResults = ParseXMLMethods.numResults(doc);

What are webservices? How we can use in Android?

A web service is any piece of software that makes itself available over the internet and uses a standardized XML messaging system. XML is used to encode all communications to a web service. For example, a client invokes a web service by sending an XML message, then waits for a corresponding XML response. Because all communication is in XML, web services are not tied to any one operating system or programming language–Java can talk with Perl; Windows applications can talk with Unix applications. Web Services are self-contained, modular, distributed, dynamic applications that can be described, published, located, or invoked over the network to create products, processes, and supply chains. These applications can be local, distributed, or Web-based. Web services are built on top of open standards such as TCP/IP, HTTP, Java, HTML, and XML. Web services are XML-based information exchange systems that use the Internet for direct application-to-application interaction. These systems can incl

Simple Json Parser in Android

Java Class:private JSONObject jObject; private String jString = "{\"itemmenu\": {" + "\"itemid\": \"file\"," + " \"itemvalue\": \"File\"," + " \"itemarray\": { \"menuitem\": " + "[ " + "{\"value\": \"New\" , " + "\"onclick\": \"CreateNewDoc()\"}, " + " {\"value\": \"Open\"," + " \"onclick\":" + " \"OpenDoc()\"}," + "{\"value\": \"Close\"," + " \"onclick\": \"CloseDoc()\"}" + "]}" + "}" + "}"; public void onCreate(Bundle savedInstanceState) {

ListView in Alphabetic Order in ANDROID

Java class:  public class MainActivity extends ListActivity { static final String[] items = new String[] { "Babbage","Boole", "Berners-Lee", "Atanasoff", "Allen","Cormack", "Cray","Dijkstra","Dix","Dewey", "Erdos","Zebra" }; ArrayAdapter<string> arrayadapter; ListView listview; ArrayList<string> arraylist; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); arraylist= new ArrayList<String>(); for(int i=0;i<items.length;i++) { arraylist.add(FRUITS[i]); } Collections.sort(arraylist );//for sorting arraylist arrayadapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,arraylist); listv

Activity Life Cycle of Android

An activity is usually a single screen that the user sees on the device at one time. An application typically has multiple activities, and the user flips back and forth among them. As such, activities are the most visible part of your application.Activity Manager is responsible for creating, destroying, and managing activities. For example, when the user starts an application for the first time, the Activity Manager will create its activity and put it onto the screen. Later, when the user switches screens, the Activity Manager will move that previous activity to a holding place. This way, if the user wants to go back to an older activity, it can be started more quickly. Older activities that the user hasn’t used in a while will be destroyed in order to free more space for the currently active one. This mechanism is designed to help improve the speed of the user interface and thus improve the overall user experience. An Activity in Android can exist in four states as d

Single Selection ListView in android

main.xml < ?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ListView android:id="@android:id/list" android:cacheColorHint="#00000000" android:scrollbars="none" android:fadingEdge="vertical" android:soundEffectsEnabled="true" android:dividerHeight="1px" android:padding="5dip" android:smoothScrollbar="true" android:layout_width="fill_parent" android:layout_height="wrap_content" android:drawSelectorOnTop="false" android:layout_marginLeft="10dip" android:l

Expandable ListView in ANDROID

java.class public class Expandablelistview extends ExpandableListActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.expandablelistview); SimpleExpandableListAdapter expListAdapter = new SimpleExpandableListAdapter( this, createGroupList(), R.layout.group_row, new String[] { "Item" }, new int[] { R.id.row_name }, createChildList(), R.layout.child_row, new String[] {"Sub Item"}, new int[] { R.id.grp_child}); setListAdapter( expListAdapter ); } // hash map for row private List createGroupList() { ArrayList result = new ArrayList(); for (int i = 0; i < 15; ++i) {