Documente Academic
Documente Profesional
Documente Cultură
Basic Application.
Android take screenshot from code
October 15, 2010 in Android Tutorial, Basic Application by S.Janardhanan The following snippet is used to create screenshot of the android device. The code uses the draw method to create a bitmap of the layout. Later the bitmap is saved a jpg image. The image is set to image view that shows the preview of the screenshot. Read the rest of this entry
Retweet
Tags: android, android game development, android mobile application, Android Tutorial, applications Comments (0)
In android, we can use some HTML Tags for text. By using HTML tag we can make a text as bold and we can change the color , etc.. Example for Android HTML View :view source print?
01 public class ExampleApp extends Activity 02 { 03 04 05 06 07 08 09 10 11 12 } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); AlertDialog.Builder ab=new AlertDialog.Builder(ExampleApp.this); ab.setMessage(Html.fromHtml("<b><font color=#ff0000> Html View " +"</font></b><br>Androidpeople.com")); ab.setPositiveButton("ok", null); ab.show();
Here i used <b> tag for Bold & <br> tag for new line in a alert dialog box. we can use this code for textview text, button text ,etc The output will looks like
Retweet
Tags: android, code, example, how to, html, html tags, source, tags, view Comments (7)
1 public class ExampleApp extends Activity { 2 @Override 3 public void onCreate(Bundle savedInstanceState) { 4 super.onCreate(savedInstanceState); 5 setContentView(R.layout.main); 6 startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:8304600889" ))); 7 } 8}
Here the sample phone number is 8304600889. You can give any phone number here. Add the below code in your AndroidManifest.XML file below to close the application tag.
view source print?
1 <uses-permission android:name="android.permission.CALL_PHONE" />
By using android.permission.CALL_PHONE only we can place a call. The output will look like
Retweet
Tags: Action, android, android.permission.CALL_PHONE, autgoing, call, how to, incoming, number, permission, phone Comments (1)
Android Widgets
January 9, 2010 in Android Tutorial, Basic Application by Sasikumar The Android widget package contains user interface elements to use on your application screen. We can design our own widget by using extend view or a subclass. The classes present under the Android widget package are:
AbsListView AbsListView.LayoutParams AbsoluteLayout AbsoluteLayout.LayoutParams AbsSeekBar AbsSpinner AdapterView<T extends Adapter> AdapterView.AdapterContextMenuInfo AlphabetIndexer AnalogClock A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
ArrayAdapter<T> AutoCompleteTextView BaseAdapter BaseExpandableListAdapter Button CheckBox CheckedTextView Chronometer CompoundButton CursorAdapter CursorTreeAdapter DatePicker DialerFilter DigitalClock EditText ExpandableListView ExpandableListView.ExpandableListContextMenuInfo Filter Filter.FilterResults FrameLayout FrameLayout.LayoutParams Gallery Gallery.LayoutParams GridView HeaderViewListAdapter HorizontalScrollView ImageButton ImageSwitcher ImageView LinearLayout LinearLayout.LayoutParams ListView ListView.FixedViewInfo MediaController MultiAutoCompleteTextView MultiAutoCompleteTextView.CommaTokenizer PopupWindow ProgressBar QuickContactBadge RadioButton RadioGroup RadioGroup.LayoutParams RatingBar RelativeLayout RelativeLayout.LayoutParams RemoteViews ResourceCursorAdapter ResourceCursorTreeAdapter Scroller ScrollView SeekBar SimpleAdapter A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
SimpleCursorAdapter SimpleCursorTreeAdapter SimpleExpandableListAdapter SlidingDrawer Spinner TabHost TabHost.TabSpec TableLayout TableLayout.LayoutParams TableRow TableRow.LayoutParams TabWidget TextSwitcher TextView TextView.SavedState TimePicker Toast ToggleButton TwoLineListItem VideoView ViewAnimator ViewFlipper ViewSwitcher ZoomButton ZoomButtonsController ZoomControls
0diggsdigg
The following snippet is used to create screenshot of the android device. The code uses the draw method to create a bitmap of the layout. Later the bitmap is saved a jpg image. The image is set to image view that shows the preview of the screenshot. ExampleScreen.java
view source print?
01 public class ExampleApp extends Activity { 02
03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
setContentView(R.layout.test);
myBtn.setOnClickListener(new View.OnClickListener() {
View v1 = view.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
<a href="http://www.androidpeople.com/wp-content/uploads/2010/10/home-screen.png"><img src="http://www.androidpeople.com/wp-content/uploads/2010/10/home-screen.png" 28 alt="Android Take screen shot from code" title="home screen" width="320" height="480" class="aligncenter size-full wp-image-1836" /></a> 29 30 31 32 33 34 35 36 37 38 } } }); } view2.setBackgroundDrawable(bitmapDrawable); view2 = (ImageView) findViewById(R.id.ImageView01);
5 6
8 </LinearLayout>
Home screen :
ScreenShot :
Retweet
1diggdigg
Moving ahead from Simple Toast Example. Here we are going to see about how to display a textview in toast using setView() & some more properties of Toast. Toast is used to display a short message or notification in quick time without any button ( like OK, Cancel ). Simple Toast To display a simple toast, we need to maKeText for that toast & then call show() to display it. To use makeText(), we need to send 3 arguments. 1) Context 2) Text to display in toast 3) Duration How much time its need to be show At last call show() to display toast.
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
Show() is used to show the toast. Toast will automatically close the dialog. */
Toast setDuration() setDuration(int) is used to set display duration of a toast. You need to set duration in int type. Toast have 2 default integers for duration 1) Toast.LENGTH_SHORT Display the toast for short time. Used when the notification text is small. 2) Toast.LENGTH_LONG Display the toast for long time. Used when the notification text is big. Custom Toast Notification Custom toast notification is used when we need to display a custom View as toast by using setView().
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
create a toast and set any view to display in setView(). Here we created a textview with some UI design to display in toast.
view source print?
01 /** Creating TextView to display in toast. 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 /** Create a Toast to display a View. * * * * Here we are going to display a TextView. Toast setView() is used to display a View. Toast Display Duration is Long. So it will display for long time. Toast setGravity() is used to set position to display the toast. */ * set Background Color, Text Color, Padding & Text for TextView. */
Toast setView() Used to display a view in toast. we can create a view with our won UI & then set it to setView() to display in view. Toast cancel() cancel() is used to stop displaying the toast if the toast is displaying.
Button.
Android Button Highlight
February 17, 2010 in Android Tutorial, Button by Sasikumar In android, we can highlight the button through custom images. Here is a example that will give you about how to set a image when the button is focused, pressed and focused pressed. we can set each image for each stage. Example for Android Button Highlight :view source print?
01 <?xml version="1.0" encoding="utf-8"?> 02 <LinearLayout android:id="@+id/LinearLayout01" 03 android:layout_width="fill_parent"
04 android:layout_height="fill_parent" 05 xmlns:android="http://schemas.android.com/apk/res/android"> 06 // Adding Button to Layout 07 <Button android:id="@+id/Button01" 08 android:background="@drawable/buttonhighlight" 09 android:layout_height="60px" 10 android:layout_width="100px"></Button> 11 </LinearLayout>
Here @drawable/buttonhighlight is a XML file located in res/drawable folder. (see below image blue color highlighted)
Create a XML file in res/drawable folder (ex:- buttonhighlight.xml) and write the code as
view source print?
01 <?xml version="1.0" encoding="utf-8"?> 02 <selector xmlns:android="http://schemas.android.com/apk/res/android">
17 </selector>
Retweet
Tags: android, android:state_focused, android:state_pressed, Button, code, example, highlight, how to, selector, source Comments (3)
03 04 05 06 07 08 09 10 11 12 }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); AlertDialog.Builder ab=new AlertDialog.Builder(ExampleApp.this); ab.setMessage(Html.fromHtml("<b><font color=#ff0000> Html View " +"</font></b><br>Androidpeople.com")); ab.setPositiveButton("ok", null); ab.show(); }
Here i used <b> tag for Bold & <br> tag for new line in a alert dialog box. we can use this code for textview text, button text ,etc The output will looks like
Retweet
Tags: android, code, example, how to, html, html tags, source, tags, view Comments (7)
print?
01 <?xml version="1.0" encoding="utf-8"?> 02 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 03 android:orientation="vertical" 04 android:layout_width="fill_parent" 05 android:layout_height="fill_parent"> 06 <Button android:id="@+id/Button01" 07 android:layout_width="wrap_content" 08 android:layout_height="wrap_content" 09 android:drawableLeft="@drawable/icon" 10 android:text="Drawable Left" /> 11 <Button android:id="@+id/Button02" 12 android:layout_width="wrap_content" 13 android:layout_height="wrap_content" 14 android:drawableRight="@drawable/icon" 15 android:text="Drawable Right" /> 16 <Button android:id="@+id/Button03" 17 android:layout_width="wrap_content" 18 android:layout_height="wrap_content" 19 android:drawableTop="@drawable/icon" 20 android:text="Drawable Top" /> 21 <Button android:id="@+id/Button04" 22 android:layout_width="wrap_content" 23 android:layout_height="wrap_content" 24 android:drawableBottom="@drawable/icon" 25 android:text="Drawable Bottom" />
26 </LinearLayout>
Retweet
Tags: android, bottom, code, drawable, example, how to, image, left, right, source, top Comments (1)
Here the button height is 50px & width is 100px The Output will look like
Retweet
Tags: android, Button, code, exapmle, height, how to, Layout, size, source, width Comments (0)
Retweet
Tags: android, background, Button, code, color, example, how to, sample, source Comments (1)
Retweet
Tags: android, background, Button, code, example, how to, image, source, widget Comments (1)
Retweet
Tags: android, Button, click, code, example, onclick, onclicklistener Comments (3)
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
By using android:background=@android:color/transparent the button background will become transparent The corresponding output will look like
35 Retweet
Tags: android, android:background, android:background="@android:color/transparent", background, Button, example, how to, transparent Comments (3)
Example:Input
view source print?
1 <TextView android:text="@+id/TextView01"
Output
By using this single line we can easily set the textcolor to anything we like.
Tags: activity, android, application, boot, launch, service, start up Comments (0)
Read the rest of this entry Retweet Tags: dom, example, sax, source code, Tutorial, XML Parsing Comments (20)
3. Note down application name and API key, do not reveal API key to anybody. Read the rest of this entry 1 Retweet Tags: facebook, fbrocket, jtwitter, post, status, Twitter Comments (29)
print?
1 public static boolean isSdPresent() { 2 3 return android.os.Environment.getExternalStorageState().equals( 4 android.os.Environment.MEDIA_MOUNTED); 5 6 }
return type boolean(true->available,false->NA). 4 Retweet Tags: android, availability, check, code, external, from, SD card, storage Comments (0)
Set TabWidget Tab Icon Set TabWidget Tab background/Color Set Current Tab
Set TabWidget Tab Icon In previous article we saw how to set text (name) to tab bar. Now we are going to see about how to set both text (name) & icon for a tab. For ex:- If the tab name is About Us you can set a icon related to About Us. To set text & icon we need to use setIndicator property. tabSpec.setIndicator(Char,Drawable); view source print?
firstTabSpec.setIndicator("First Tab Name", getResources().getDrawable(R.drawable.logo)); secondTabSpec.setIndicator("Second Tab Name", 2 getResources().getDrawable(R.drawable.logo)); 1
Read the rest of this entry Retweet Tags: code, example, source, tab, tab host, TabBar, tabwidget Comments (17)
We hardly use coding in the tutorial most of the part are designed in XML layout itself. Read the rest of this entry 3 Retweet Tags: android, container, drawer, example, handler, how to, sliding, Tutorial Comments (22)
1diggdigg 1 Hi Android Developers, In this post we will discuss on the methods to create a file in SD card. In this series we will create a csv file and save it in SD card. If you are trying the following snippet in Emulator then make sure you have created a AVD with SD card. These are the steps to create AVD with SD card in eclipse. Step 1: Eclipse->Window->Android SDK and AVD manager->Virtual Devices.
Step 2: Give the AVD name, Select your Target and give 1024 in the SD card size space.So that it create a SD card
Step 3: To create a file make sure u have added the following Manifest permission view source print?
1 android.permission.WRITE_EXTERNAL_STORAGE
Step 4: To use the created SD card we have to use the function Environment.getExternalStorageDirectory() The csv file will be much important for android application developer in case of exporting the DB content and also creating report. We will do that in the next part. Now we just create a simple CSV file. Use the following snippet to create a CSV file. view source print?
01 package com.csvtry;
02 03 import java.io.File; 04 import java.io.FileWriter; 05 import java.io.IOException; 06 07 import android.app.Activity; 08 import android.os.Bundle; 09 import android.os.Environment; 10 11 public class csvtry extends Activity { 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 //generate whatever data you want writer.append("Froyo"); writer.append(','); writer.append("2.2"); writer.append('\n'); writer.append("Eclairs"); writer.append(','); writer.append("2.1"); writer.append('\n'); writer.append("SDK Name"); writer.append(','); writer.append("SDK Number"); writer.append('\n'); } private static void generateCsvFile(String sFileName) { try { File root = Environment.getExternalStorageDirectory(); File gpxfile = new File(root, sFileName); FileWriter writer = new FileWriter(gpxfile); generateCsvFile("androidpeople.csv"); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);
46 47 48 49 50 51 52 53 54 } }
There is always necessity to add extra keys apart from default keys available in virtual QWERTY keyboard. For instance we may need a direct search key by the side of edit text box in order to have direct triggering of Search actions. For Instance to add a Search key we need to add this code, so that It may appear in the QWERTY board.
EditTextSample.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
The peculiar behavior of the button is that It closes the keyboard upon clicking this DONE key. For adding a Next box EditTextSample.setImeOptions(EditorInfo.IME_ACTION_NEXT); These similar can also be set through XML attribute. Search :
<EditText android:text="@+id/EditText01" android:id="@+id/EditText01" android:layout_height="wrap_content" android:layout_width="fill_parent" android:imeOptions="actionSearch"></EditText>
Done:
<EditText android:text="@+id/EditText01" android:id="@+id/EditText01" android:layout_height="wrap_content" android:layout_width="fill_parent" android:imeOptions="actionDone"></EditText>
Next:
<EditText android:text="@+id/EditText01" android:id="@+id/EditText01" android:layout_height="wrap_content" android:layout_width="fill_parent" android:imeOptions="actionNext"></EditText>
The similar kind action can be set through IME options in edit text properties.
Search Power button Audio volume up button Audio volume down button Camera button
Switch to previous layout orientation (for example, portrait, landscape) KEYPAD_7, Ctrl-F11 Switch to next layout orientation (for example, portrait, landscape) Toggle cell networking on/off Toggle code profiling Toggle fullscreen mode Toggle trackball mode Enter trackball mode temporarily (while key is pressed) DPad left/up/right/down DPad center click Onion alpha increase/decrease KEYPAD_9, Ctrl-F12 F8 F9 (only with -trace startup option) Alt-Enter F6 Delete KEYPAD_4/8/6/2 KEYPAD_5 KEYPAD_MULTIPLY(*) / KEYPAD_DIVIDE(/)
when using keypad key just disable your NumLock and then used it.
2 Retweet
Tags: android, done, Editorinfo, Edittext, enter, example, imeoption, next, replace, search, virtual keyboard Comments (4)
1diggdigg
Moving ahead from TabHost Tutorial Part 1, here we are going to see about few needed things for Tab Bar Design.
Set TabWidget Tab Icon Set TabWidget Tab background/Color Set Current Tab
Set TabWidget Tab Icon In previous article we saw how to set text (name) to tab bar. Now we are going to see about how to set both text (name) & icon for a tab. For ex:- If the tab name is About Us you can set a icon related to About Us. To set text & icon we need to use setIndicator property. tabSpec.setIndicator(Char,Drawable);
view source print?
1 firstTabSpec.setIndicator("First Tab Name", getResources().getDrawable(R.drawable.logo));
Set Current Tab We can manually set any tab to visible at first view.
view source print?
1 tabHost.getTabWidget().setCurrentTab(1);
we can use setCurrentTab() in run time too. Set TabWidget Tab Background / Color In default android tab bar color will be in Grey, you can easily change the color of the tab bar. It will be very useful when you are using different UI graphics for your App. use the below line of code in onCreate() to display in first time.
view source print?
1 for(int i=0;i<tabHost.getTabWidget().getChildCount();i++) 2{ 3 tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#7392B 5"));
4 }
Here 0 position is the first tab. When you change the tab selection you need to change your selected color to that current tab & replace the default color to other tab. For that use OnTabChangeListener(). These method will be called when you change the tab selection.
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
Screenshot
02 03 <LinearLayout android:id="@+id/LinearLayout01" 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 <LinearLayout android:id="@+id/LinearLayout02" android:layout_width="wrap_content" android:layout_height="wrap_content"> <ViewFlipper android:id="@+id/ViewFlipper01" android:layout_width="wrap_content" android:layout_height="wrap_content"> <!--adding views to ViewFlipper--> <TextView android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Flipper Content 1"></TextView> <TextView android:id="@+id/TextView02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Flipper Content 2"></TextView> <TextView android:id="@+id/TextView03" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Flipper Content 3"></TextView> android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical"> <LinearLayout android:id="@+id/LinearLayout03" android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Next"></Button> <Button android:id="@+id/Button02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Previous"></Button> </LinearLayout>
26 27 28
</ViewFlipper> </LinearLayout>
29 </LinearLayout>
19 20 21 22 23 24 25 26 27 28 29 30 } } } } if (v == previous) { vf.showPrevious(); @Override public void onClick(View v) { // TODO Auto-generated method stub if (v == next) { vf.showNext();
1diggdigg
The following is an tutorial to create short links. Why do we need shortlinks? consider this link http://www.google.com/search?q=android+url+shortener&ie=utf-8&oe=utf8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a This url has 132 characters. This is too large to use in application. Thats y we need to short it.
So the above url will be shortened as http://tinyurl.com/2vw3t8j
URL shortners are the one of the most demanding concept widely used in sharing sites like Facebook and Twitter. To start with make sure you have added the internet permission to your application.
view source print? A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
1 <uses-permission android:name="android.permission.INTERNET"></uses-permission>
Step1: The basic step is that our url is to be sent to tinyurl http://tinyurl.com/api-create.php?url= using this URL. Step2: The custom url is encoded with tinyurl using the function String.format(tinyurl, URLEncoder.encode(original)); Step 3: The url is sent in Get method using the HttpGet object with function client.execute() Step 4: The output is read from the HttpResponse.And stored as string using the InputStream. Step 5: The url is shortened and will be redirected to webpage upon clicking the url.
view source print?
01 public static String CreateUrl(String original) 02 { 03 String tinyUrl = null; 04 try { 05 06 HttpClient client = new DefaultHttpClient(); 07 String urlTemplate = "http://tinyurl.com/api-create.php?url=%s"; 08 String uri = String.format(urlTemplate, URLEncoder.encode(original)); 09 HttpGet request = new HttpGet(uri); 10 HttpResponse response = client.execute(request); 11 HttpEntity entity = response.getEntity();
12 InputStream in = entity.getContent(); 13 try { 14 StatusLine statusLine = response.getStatusLine(); 15 int statusCode = statusLine.getStatusCode(); 16 if (statusCode == HttpStatus.SC_OK) 17 { 18 // TODO: Support other encodings 19 String enc = "utf-8"; 20 Reader reader = new InputStreamReader(in, enc); 21 BufferedReader bufferedReader = new BufferedReader(reader); 22 tinyUrl = bufferedReader.readLine(); 23 if (tinyUrl != null) 24 { 25 System.out.println("Created Url-"+tinyUrl); 26 } 27 else { 28 throw new IOException("empty response"); 29 } 30 } 31 else { 32 String errorTemplate = "unexpected response: %d"; 33 String msg = String.format(errorTemplate, statusCode); 34 throw new IOException(msg); 35 } 36 } 37 finally {
0diggsdigg
Mobile applications are much in need of notifications to draw the attention of the user on occurrence of an event. The notifications are needed to be invoked by our application to make the user to interact to application and proceed ahead for computation. So here is a simple example for a message notification with a sound as when you click a button.
view source print? 01 package com.notify; 02 03 import android.app.Activity; 04 import android.app.Notification; 05 import android.app.NotificationManager; 06 import android.app.PendingIntent; 07 import android.content.Context; 08 import android.content.Intent; 09 import android.net.Uri; 10 import android.os.Bundle; 11 import android.view.View; 12 import android.view.View.OnClickListener; 13 import android.widget.Button; 14 15 public class notify extends Activity { 16
17 private NotificationManager mNotificationManager; 18 private int SIMPLE_NOTFICATION_ID; 19 20 /** Called when the activity is first created. */ 21 @Override 22 public void onCreate(Bundle savedInstanceState) { 23 super.onCreate(savedInstanceState); 24 setContentView(R.layout.main); 25 26 mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); 27 28 final Notification notifyDetails = new Notification(R.drawable.arrow,"New Alert, Click Me!",System.currentTimeMillis());
29 30 long[] vibrate = {100,100,200,300}; 31 notifyDetails.vibrate = vibrate; 32 notifyDetails.defaults =Notification.DEFAULT_ALL; 33 Context context = getApplicationContext(); 34 35 Button start = (Button)findViewById(R.id.btn_showsample); 36 Button cancel = (Button)findViewById(R.id.btn_clear); 37 38 start.setOnClickListener(new OnClickListener() { 39 40 public void onClick(View v) {
41 42 Context context = getApplicationContext(); 43 CharSequence contentTitle = "Androidpeople.com Simple Notification"; 44 CharSequence contentText = "Get back to Application on clicking me"; 45 46 Intent notifyIntent = new Intent(context, notify.class); 47 48 PendingIntent intent = 49 PendingIntent.getActivity(notify.this, 0, 50 notifyIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK); 51 52 notifyDetails.setLatestEventInfo(context, contentTitle, contentText, intent); 53 54 mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails); 55 56 } 57 }); 58 59 cancel.setOnClickListener(new OnClickListener() { 60 61 public void onClick(View v) { 62 63 mNotificationManager.cancel(SIMPLE_NOTFICATION_ID); 64 } 65 });
66 } 67 }
CheckBox.
Android Checkbox Default Checked
February 19, 2010 in Android Tutorial, CheckBox by Sasikumar In the previous post about checkbox, we already saw about the Android Checkbox Example Now we are going to see about how to set default check value to the checkbox. In android, when we are showing the checkbox we may need to check default one of the checkbox. In that time we can use android:checked checkbox property. Example for Android Checkbox Default Checked :view source print? A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
01 <?xml version="1.0" encoding="utf-8"?> 02 <LinearLayout android:id="@+id/LinearLayout01" 03 android:layout_width="fill_parent" 04 android:layout_height="fill_parent" 05 xmlns:android="http://schemas.android.com/apk/res/android" 06 android:orientation="vertical"> 07 <CheckBox android:id="@+id/CheckBox01" 08 android:layout_width="wrap_content" 09 android:layout_height="wrap_content" 10 // Here Checked box is checked default 11 android:checked="true" 12 android:text="Default Checked" /> 13 <CheckBox android:id="@+id/CheckBox02" 14 android:layout_width="wrap_content" 15 android:layout_height="wrap_content" 16 android:text="Default not Checked" /> 17 </LinearLayout>
Retweet
Tags: android, CheckBox, checked, code, default, example, how to, source Comments (0)
04 android:orientation="vertical">
05 <CheckBox android:id="@+id/check1" 06 android:layout_width="wrap_content" 07 android:layout_height="wrap_content" android:text="Android" /> 08 <CheckBox android:id="@+id/check2" 09 android:layout_width="wrap_content" 10 android:layout_height="wrap_content" android:text="iPhone" /> 11 <Button android:id="@+id/button1" 12 android:layout_width="wrap_content" 13 android:layout_height="wrap_content" android:text="Confirm Selection"/> 14 <TextView android:id="@+id/TextView01" android:layout_width="wrap_content" 15 android:layout_height="wrap_content" android:text="Selected is" /> 16 <EditText android:id="@+id/text1" 17 android:layout_width="wrap_content" 18 android:layout_height="wrap_content" android:text="EditText" 19 android:textSize="18sp"/> 20 </LinearLayout>
07 @Override 08 public void onCreate(Bundle icicle) 09 { 10 super.onCreate(icicle); 11 setContentView(R.layout.main); 12 et1 = (EditText) this.findViewById(R.id.text1); 13 c1 = (CheckBox) findViewById(R.id.check1); 14 c2 = (CheckBox) findViewById(R.id.check2); 15 b1 = (Button) findViewById(R.id.button1); 16 b1.setOnClickListener(this); 17 } 18 19 @Override 20 public void onClick(View arg0) { 21 // TODO Auto-generated method stub 22 et1.setText(""); 23 if (c1.isChecked()) 24 et1.setText("Android "); 25 if (c2.isChecked()) 26 et1.setText(et1.getText()+"iPhone "); 27 } 28 }
Gravity is used to align a view in proper way. It may helps us in UI part very much. Gravity have some option like top, left, center, right, bottom, center-vertical, etc You can use any option to gravity according to your UI Design.
android:layout_height="wrap_content" android:text="Left & Center Gravity"></TextView> </LinearLayout> <LinearLayout android:id="@+id/LinearLayout04" android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center"> <TextView android:id="@+id/TextView04" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Center Gravity"></TextView> </LinearLayout> <LinearLayout android:id="@+id/LinearLayout05" android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="right|center"> <TextView android:id="@+id/TextView05" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/icon_1"></TextView> <TextView android:id="@+id/TextView06" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Right & Center Gravity"></TextView> </LinearLayout> <LinearLayout android:id="@+id/LinearLayout06" android:layout_width="fill_parent" android:gravity="bottom" android:layout_height="50px"> <TextView android:id="@+id/TextView08" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Bottom Gravity"></TextView> </LinearLayout> </LinearLayout>
Today we are going to see about how to set a image as wallpaper in 2 line of code in android. we can easily set any image from your res folder as a wallpaper in a 2 line of code. First step is you need to change your image as Bitmap, then use getApplicationContext() to set your wallpaper. Thats it!
import java.io.IOException; import import import import import import import import android.app.Activity; android.graphics.Bitmap; android.graphics.BitmapFactory; android.os.Bundle; android.view.View; android.view.View.OnClickListener; android.widget.Button; android.widget.ImageView;
public class ExampleApp extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.test); ImageView imageView = (ImageView) findViewById(R.id.ImageView01); imageView.setBackgroundResource(R.drawable.gall_2); Button button = (Button) findViewById(R.id.Button01); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Bitmap bitmap = BitmapFactory.decodeStream(getResources()
test.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/LinearLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical"> <Button android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Set as Wallpaper"></Button> <ImageView android:id="@+id/ImageView01" android:layout_width="wrap_content" android:layout_height="wrap_content"></ImageView> </LinearLayout>
1diggdigg
Today we are going to see about AudioManager uses. AudioManager provides access to volume and ringer mode control. Use
view source print?
1 Context.getSystemService(Context.AUDIO_SERVICE)
to get an instance of AudioManager Class. AudioManager have more features. In that we are going to see about setRingerMode(int RingerMode); setRingerMode() is used to control the ring tone. If you need to stop a incoming call ring tone through your code you can use this method. 2 line of code to stop incoming call ring tone.
view source print?
1 AudioManager aManager=(AudioManager)getSystemService(AUDIO_SERVICE); 2 aManager.setRingerMode(aManager.RINGER_MODE_SILENT);
RINGER_MODE_SILENT will set ringer mode to silent. You may also use
view source print?
1 AudioManager aManager=(AudioManager)getSystemService(AUDIO_SERVICE); 2 aManager.setRingerMode(aManager.RINGER_MODE_VIBRATE);
1diggdigg 2
Today we are going to see about, How to use different layout when screen orientation changes from Portrait to Landscape or Landscape to Portrait. For example :In portrait mode , the option page button will looks like nice when buttons are in one by one position. But in landscape if we use the same process we need to have scrollview to see all the option button in the page. To overcome this problem here is a easy solution. In your res folder create two folders for Landscape 1) drawable-land 2) layout-land drawable-land folder images is used when the phone orientation in landscape mode. layout-land folder layout files is used when the phone orientation in landscape mode.
Retweet
text textCapCharacters textCapWords textCapSentences textAutoCorrect textAutoComplete textMultiLine textImeMultiLine textNoSuggestions textUri textEmailAddress textEmailSubject textShortMessage textLongMessage textPersonName textPostalAddress textPassword textVisiblePassword textWebEditText A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
Here the inputType is Number. You can set one or more inputType to a edittext at a time. The Output will look like
Retweet
Tags: android, code, Edittext, how to, inputtype, multipleline, number, numeric, phone, program, source, uri 2 Comments
When you start typing in editext the hint will be auto hidden.
Retweet
Tags: android, code, Edittext, example, hint, how to, source 2 Comments
Here singleline property is true. So it wont create a new line in edittext. The Output will look like
Here the text is Edittext example by www.androidpeople.com but it is showing Edittext example by www.android as the singleline property is true. If singleline property is false , the output will look like
Retweet
Tags: android, code, Edittext, example, how to, line, single, singleline, source 1 Comment
Here the numeric is both interger & decimal. So it will accept only the integer & decimal values. We will be unable to type characers in edittext. We can use only 0-9 & .in edittext The Output will look like
Retweet
Tags: android, code, decimal, Edittext, example, how to, integer, numeric, source 1 Comment
We just need to set android:password=true to make your edittext to password. The Output will look like
Retweet
Output
Here the Hexadecimal value of the Color we used is #23cf34 android:textColor=#23cf34 By using this single line we can easily set the textcolor to anything we like.
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
Retweet
After Starting the Emulator, Press Menu Button -> Settings (See below image) A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
Go to Settings -> Applications Then go to Applications -> Manage Applications From that Manage Application, select the application you need to manage. (In the below image, we have selected the Spinner Example Application to manage).
By Selecting the application you will get a application info window to manage. Here Press the Uninstall button to uninstall the application. When it confirms the uninstall, just Press Ok Button to continue uninstall or Press Cancel Button to cancel the action.
Retweet
Tags: android, application, delete, emulator, how to, remove, uninstall No Comments
This post is posted as per the request of many comments on Android JTwitter Example. Now let proceed ahead with Facebook using FBrocket. Using FB rocket we can update our facebook profile status from mobile application. Before we get into coding we got to make sure that we do the following steps
1. Import the FBrocket JAR file to the eclipse project and add it to JAR libraries. Download here ( http://www.xeomax.net/fbrocket/download.php?d=bin&v=0.1a ) 2. Make sure you have created an application in http://www.facebook.com/developers/#!/developers/createapp.php 3. Note down application name and API key, do not reveal API key to anybody.
package org.androidpeople.facebook; import net.xeomax.FBRocket.FBRocket;
public class FacebookRocketExample extends Activity implements LoginListener { private FBRocket fbRocket; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); shareFacebook(); } public void shareFacebook() { fbRocket = new FBRocket(this, "Your App Name", "Your API Key"); if (fbRocket.existsSavedFacebook()) { fbRocket.loadFacebook(); } else { fbRocket.login(R.layout.main); } } @Override public void onLoginFail() { fbRocket.displayToast("Login failed!"); fbRocket.login(R.layout.main); } @Override public void onLoginSuccess(Facebook facebook) { // TODO Auto-generated method stub fbRocket.displayToast("Login success!"); try { facebook.setStatus("This is your status"); fbRocket.displayDialog("Status Posted Successfully!! " + facebook.getStatus()); } catch (ServerErrorException e) { if (e.notLoggedIn()) { fbRocket.login(R.layout.main); } else { System.out.println(e); } } } }
Screenshots :
0diggsdigg
This article is next step of Listexample. Here we have a search box which sorts the list view as when the content matches the list items. Why do we need this? Imagine that if we have 2K to 3K items in the listview, It will not be possible to scrolldown till 2000th item.In this case this will be handy to cut short items. To start with we add a edittext box and Listview added to LinearLayout.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/LinearLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical"> <EditText android:id="@+id/EditText01" android:layout_height="wrap_content" android:layout_width="fill_parent" android:hint="Search"></EditText><ListView android:id="@+id/ListView01" android:layout_width="wrap_content" android:layout_height="wrap_content" ></ListView> </LinearLayout>
Have a sample String array that is to loaded as List items. Create a temporary arraylist that hold the sorted items and Simply add it to the list view on addTextChangedListener() of edit text.
package com.androidpeople; import java.util.ArrayList; import import import import import import import android.app.Activity; android.os.Bundle; android.text.Editable; android.text.TextWatcher; android.widget.ArrayAdapter; android.widget.EditText; android.widget.ListView;
public class searchsort extends Activity { /** Called when the activity is first created. */ private ListView lv1; private EditText ed; private String lv_arr[]={"Android","Cupcake","Donut","Eclairs","AndroidPeople","Froyo",}; private ArrayList<String> arr_sort= new ArrayList<String>(); int textlength=0; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); lv1=(ListView)findViewById(R.id.ListView01); ed=(EditText)findViewById(R.id.EditText01); // By using setAdpater method in listview we an add string array in list. lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr)); ed.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { } public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
public void onTextChanged(CharSequence s, int start, int before, int count) { textlength=ed.getText().length(); arr_sort.clear(); for(int i=0;i<lv_arr.length;i++) { if(textlength<=lv_arr[i].length()) { if(ed.getText().toString().equalsIgnoreCase((String) lv_arr[i].subSequence(0, textlength))) { arr_sort.add(lv_arr[i]); } } } lv1.setAdapter(new ArrayAdapter<String>(searchsort.this,android.R.layout.simple_list_item_1 , arr_sort)); } }); } }
Layout.
Android Layout Padding
February 11, 2010 in Android Tutorial, Layout, RelativeLayout, TableLayout by Sasikumar
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
In android, we can set Padding to layout. So that for each view we can give some space to display. We can set padding for each side separately. Example for Android Layout Padding :view source print?
01 <?xml version="1.0" encoding="utf-8"?> 02 <LinearLayout android:id="@+id/LinearLayout01" 03 android:layout_width="fill_parent" 04 android:layout_height="fill_parent" 05 xmlns:android="http://schemas.android.com/apk/res/android" 06 android:paddingLeft="5px" 07 android:paddingRight="5px" 08 android:paddingTop="10px" 09 android:paddingBottom="10px"> 10 <TextView android:id="@+id/TextView01" 11 android:layout_width="wrap_content" 12 android:layout_height="wrap_content" 13 android:text="Androidpeople.com" /> 14 </LinearLayout>
Retweet
Tags: align, android, code, how to, Layout, padding, source Comments (2)
04 android:layout_height="fill_parent" 05 xmlns:android="http://schemas.android.com/apk/res/android" 06 android:background="@drawable/bbg"> 07 <Button android:text="@+id/Button01" 08 android:id="@+id/Button01" 09 android:layout_width="wrap_content" 10 android:layout_height="wrap_content" /> 11 </LinearLayout>
Retweet
Tags: android, background, code, color, example, how to, image, Layout, source Comments (2)
So that when you click the layout it will be highlighted as like a listview highlight. Example for Android Layout Highlight :view source print?
01 <?xml version="1.0" encoding="utf-8"?> 02 <LinearLayout android:id="@+id/LinearLayout01" 03 android:layout_width="fill_parent" 04 android:layout_height="fill_parent" 05 xmlns:android="http://schemas.android.com/apk/res/android"> 06 <LinearLayout android:id="@+id/LinearLayout02" 07 android:layout_height="50px" 08 android:layout_width="fill_parent" 09 // Layout Click enable 10 android:clickable="true" 11 // Setting Highlight Option in background property 12 android:background="@android:drawable/list_selector_background" /> 13 </LinearLayout>
we can set this background to any layout. The output will looks like
Retweet
Tags: android, example, highlight, how to, Layout, source Comments (2)
1 Retweet
Tags: android, background, code, color, example, how to, Layout, linear, relative, source, table Comments (2)
Android RelativeLayout
December 23, 2009 in Android Tutorial, Layout, RelativeLayout by Sasikumar RelativeLayout: What are the uses of Relative layout?
By adding views to relative layout, we can set the relative positions of views with respect to each other. For example if we add three views like imageview, textview and edittext we can specify the position of textview, that is whether it should be below (or any other direction) to edittext or imageview. android:layout_above=@+id/idname (Here @+id/idname is the id name of the view that should be above it). We can also set the position by android:layout_ toLeftOf (or) toRightOf (or) below and above.
01 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 02 android:layout_width="fill_parent" 03 android:layout_height="?android:attr/listPreferredItemHeight" 04 android:padding="6dip"> 05 <ImageView android:id="@+id/logo" 06 android:layout_width="wrap_content" 07 android:layout_height="fill_parent" 08 android:layout_alignParentTop="true" 09 android:layout_alignParentBottom="true" 10 android:layout_marginRight="6dip" 11 android:src="@drawable/logo" /> 12 <TextView android:id="@+id/bodycontent" 13 android:layout_width="fill_parent" 14 android:layout_height="26dip" 15 android:layout_alignParentBottom="true" 16 android:layout_alignParentRight="true" 17 android:singleLine="true" 18 android:ellipsize="marquee" 19 android:text="Body Content" 20 android:layout_toRightOf="@+id/logo"/> 21 <TextView android:layout_width="fill_parent" 22 android:layout_height="wrap_content" 23 android:layout_alignParentRight="true" 24 android:layout_alignParentTop="true" 25 android:layout_alignWithParentIfMissing="true" 26 android:gravity="center_vertical"
(Note: Here the red color lines wont appear in the output. ) In this example you can see that I first added the Body Content textview. But it is showing below the title & next to logo. This is the main use of relative layout. We can alter the position to any directions (right, left, below & above). Android TableLayout
Retweet
Tags: android, android:layout, example, Layout, position, program, relative, RelativeLayout, relativelayout example Comments (0)
Android TableLayout
December 23, 2009 in Android Tutorial, Layout, TableLayout by admin
TableLayout:
By seeing the word Table itself we know that Table Layout is used to show views in a table format with rows & columns. How to add rows in a table layout?
TableRow is used to add rows in a table layout. TableRow is a layout. It will arrange its children horizontally. If the table row parent is not table layout, then it will work like a horizontal linear layout. Each TableRow will define a single row in table. (If we create 10 TableRows it will define 10 rows in a table).
We can use any view to add a column in TableRow. We can add multiple columns by adding multiple views in a TableRow.
For instance,
view source print?
01 <?xml version="1.0? encoding="utf-8??> 02 <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" 03 android:layout_width="fill_parent" 04 android:layout_height="fill_parent" 05 android:stretchColumns="1?> 06 <TableRow> 07 <TextView android:text="New" 08 android:padding="3dip" /> 09 <TextView android:text="Ctrl+N" 10 android:gravity="right" 11 android:padding="3dip" /> 12 </TableRow> 13 <TableRow> 14 <TextView android:text="Import"
15 android:padding="3dip" /> 16 </TableRow> 17 <TableRow> 18 <TextView android:text="Exit" 19 android:padding="3dip" /> 20 <TextView android:text="Ctrl+E" 21 android:gravity="right" 22 android:padding="3dip" /> 23 </TableRow> 24 </TableLayout>
(Note: The red color lines wont appear in output) Here new, import & exit are of different lengths but it is showing them as the same size because of TableRow. By using TableRow we can get the values in order neatly & easily. Android RelativeLayout
Main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/LinearLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical"> <Gallery xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/examplegallery" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <ImageView android:id="@+id/ImageView01" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>
Java file
public class GalleryExample extends Activity { private Gallery gallery; private ImageView imgView; private Integer[] Imgid = { R.drawable.a_1, R.drawable.a_2, R.drawable.a_3, R.drawable.a_4, R.drawable.a_5, R.drawable.a_6, R.drawable.a_7 }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); imgView = (ImageView)findViewById(R.id.ImageView01); imgView.setImageResource(Imgid[0]); gallery = (Gallery) findViewById(R.id.examplegallery); gallery.setAdapter(new AddImgAdp(this)); gallery.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView parent, View v, int position, long id) { imgView.setImageResource(Imgid[position]); } }); } public class AddImgAdp extends BaseAdapter { int GalItemBg; private Context cont; public AddImgAdp(Context c) { cont = c; TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme); GalItemBg = typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0); typArray.recycle(); } public int getCount() { return Imgid.length; }
public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ImageView imgView = new ImageView(cont); imgView.setImageResource(Imgid[position]); imgView.setLayoutParams(new Gallery.LayoutParams(80, 70)); imgView.setScaleType(ImageView.ScaleType.FIT_XY); imgView.setBackgroundResource(GalItemBg); return imgView; } } }
Tags: android, Android Tutorial, attrs.xml, example, Gallery, imageview, style Comments (32)
7 </resources>
07 08 09
10 </LinearLayout>
19 20 21 22 23 24 25 26 27 28 29 gallery.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView parent, View v, int position, long id) { gallery = (Gallery) findViewById(R.id.examplegallery); gallery.setAdapter(new AddImgAdp(this)); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);
30 // Displaying the position when the gallery item in clicked 31 32 33 34 35 36 37 38 39 40 41 // Adding images. 42 43 private Integer[] Imgid = { R.drawable.a_1, R.drawable.a_2, R.drawable.a_3, R.drawable.a_4, public class AddImgAdp extends BaseAdapter { int GalItemBg; private Context cont; } }); Toast.makeText(GalleryExample.this, "Position=" + position, Toast.LENGTH_SHORT).show(); }
R.drawable.a_5, R.drawable.a_6, R.drawable.a_7 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 public View getView(int position, View convertView, ViewGroup parent) { ImageView imgView = new ImageView(cont); } public long getItemId(int position) { return position; } public Object getItem(int position) { return position; } public int getCount() { return Imgid.length; } public AddImgAdp(Context c) { cont = c; TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme); GalItemBg = typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0); typArray.recycle(); };
68
imgView.setImageResource(Imgid[position]);
69 // Fixing width & height for image to display 70 71 72 73 74 75 76 77 78 } } } return imgView; imgView.setLayoutParams(new Gallery.LayoutParams(80, 70)); imgView.setScaleType(ImageView.ScaleType.FIT_XY); imgView.setBackgroundResource(GalItemBg);
media.
Java File
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
12 // Set video link (mp4 format ) 13 14 15 16 17 18 19 } } Uri video = Uri.parse("mp4 video link"); videoView.setMediaController(mediaController); videoView.setVideoURI(video); videoView.start();
Try this!..
Retweet
Tags: audio, code, example, how to, media, player, playing, source, Video, view Comments (27)
Now Run the Application. After the application starts , the media player will starts automatically and song will be played. To stop playing the song use mPlayer.stop();
MediaPlayer.
Android MediaPlayer Example
March 9, 2010 in Android Tutorial, MediaPlayer, Tutorial, media by Sasikumar In android, we can play the audio file from the resource. How to do it ? Step1:- In your project , create a folder named with raw in res folder (res > raw). In that folder copy any mp3 file to play.
10 11 }
Now Run the Application. After the application starts , the media player will starts automatically and song will be played. To stop playing the song use mPlayer.stop();
Retweet
RadioButton.
Android Dialog with Select Option
February 6, 2010 in Android Tutorial, Dialog, RadioButton by Sasikumar In android, by using dialog we can select a option from multiple option using radio buttons. Example for Dialog with select option :view source print?
01 public class ExampleApp extends Activity 02 { 03 04 05 06 07 08 09 10 11 12 13 AlertDialog.Builder ab=new AlertDialog.Builder(ExampleApp.this); ab.setTitle("Title"); ab.setSingleChoiceItems(items, 0,new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { final String items[] = {"item1","item2","item3"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 } } }); ab.show(); } }) }) }
// onClick Action
.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // on Ok button action }
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // on cancel button action
Retweet
Tags: android, code, Dialog, example, how to, negativebutton, option, positivebutton, radio button, select, source Comments (4)
05 06 07 08 09 10 11 12 13 14 15 16 17 18 } }
setContentView(R.layout.main); final CharSequence[] PhoneModels = {"iPhone", "Nokia", "Android"}; AlertDialog.Builder alt_bld = new AlertDialog.Builder(this); alt_bld.setIcon(R.drawable.icon); alt_bld.setTitle("Select a Phone Model"); alt_bld.setSingleChoiceItems(PhoneModels, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { Toast.makeText(getApplicationContext(), "Phone Model = "+PhoneModels[item], Toast.LENGTH_SHORT).show(); } }); AlertDialog alert = alt_bld.create(); alert.show();
Retweet
Tags: alert, android, builder, Button, code, Dialog, example, how to, radio, RadioButton, setSingleChoiceItems, source Comments (11)
02 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 03 android:orientation="vertical" android:layout_width="fill_parent" 04 android:layout_height="fill_parent"> 05 <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textStyle="bold" android:text="APK Extension?" />
06 <RadioGroup android:layout_width="fill_parent" 07 android:layout_height="wrap_content" 08 android:orientation="vertical" 09 android:id="@+id/QueGroup1"> 10 <RadioButton android:checked="false" 11 android:id="@+id/option1" android:text="Android Package"/> 12 <RadioButton android:checked="false" 13 android:id="@+id/option2" android:text="Android Platform"/> 14 </RadioGroup> 15 <LinearLayout android:layout_width="fill_parent" 16 android:layout_height="fill_parent" android:orientation="vertical"> 17 <TextView android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Selected is : "></TextView>
20 </LinearLayout> 21 </LinearLayout>
02 { 03 private RadioButton rb1; 04 private RadioButton rb2; 05 private Button b1; 06 private TextView t1; 07 08 @Override 09 public void onCreate(Bundle savedInstanceState) { 10 super.onCreate(savedInstanceState); 11 setContentView(R.layout.main); 12 rb1=(RadioButton)findViewById(R.id.option1); 13 rb2=(RadioButton)findViewById(R.id.option2); 14 b1=(Button)findViewById(R.id.selected); 15 b1.setOnClickListener(this); 16 t1=(TextView)findViewById(R.id.TextView01); 17 } 18 19 @Override 20 public void onClick(View v) { 21 if(v == b1) 22 { 23 if(rb1.isChecked() == true) 24 t1.setText("Selected is : "+rb1.getText()); 25 if(rb2.isChecked() == true) 26 t1.setText("Selected is : "+rb2.getText()); 27 }
28 } 29 }
screen.
Get the screen size in Android
December 20, 2009 in Android Tutorial, screen by admin Android screen size is different for different phone models. There are some screen resolutions already defined in Android. They are:
QVGA (240320, low density, small screen) WQVGA (240400, low density, normal screen) FWQVGA (240432, low density, normal screen) HVGA (320480, medium density, normal screen) WVGA800 (480800, high density, normal screen) WVGA854 (480854 high density, normal screen)
02 public void onCreate(Bundle savedInstanceState) { 03 super.onCreate(savedInstanceState); 04 setContentView(R.layout.main); 05 int ht; 06 int wt; 07 DisplayMetrics displaymetrics = new DisplayMetrics(); 08 getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); 09 ht = displaymetrics.heightPixels; 10 wt = displaymetrics.widthPixels; 11 }
Here, ht will return the height & wt will return the width.
android:layout_width="400px" /> <Button android:text="3" android:id="@+id/Button03" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> </HorizontalScrollView> </ScrollView> </LinearLayout>
Retweet
Tags: android, code, example, horizontal, horizontalscrollview, how to, Scroll, scrollview, source 4 Comments
xmlns:android="http://schemas.android.com/apk/res/android"> <ScrollView android:id="@+id/ScrollView01" android:layout_width="fill_parent" android:layout_height="110px"> <LinearLayout android:id="@+id/LinearLayout02" android:layout_width="wrap_content" android:layout_height="30px" android:orientation="vertical"> <Button android:text="1" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:text="2" android:id="@+id/Button02" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:text="3" android:id="@+id/Button03" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> </ScrollView> </LinearLayout>
Retweet
Tags: android, code, example, how to, Scroll, scrollview, source, view 4 Comments
You can also customize your listview. Click here to see custom listview example The output will look like
Retweet
Tags: adapter, android, array, arrayadapter, code, example, how to, list, Listview, source, view 62 Comments
Spinner.
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
Here I choose the 2nd value. So the corresponding output value is 3. The output will look like
Retweet
Tags: android, code, default, example, how to, setselection, source, Spinner, value No Comments
In Android, Spinner is nothing but a combo box or list box. It lets you viewing multiple items and allows you to select one item from the list. Edit Your XML code like this
<Spinner android:id="@+id/Spinner01" android:layout_width="wrap_content" android:layout_height="wrap_content" />
Here the tablelayout background color is green & textview background color is black. By using android:layout_marginTop,Right,Bottom,Left as 3px. It will look like a border for textview. The Output will look like
1 Retweet
Tags: android, border, code, example, how to, Layout, source, table, Textview Comments (0)
android:textSize for Textview Size android:textStyle for Textview Text Style android:typeface for Textview Font Style
Here the Textview size is 20px , Textview text style is bold & textview font style is Serif. We can set textStyle as Normal, Bold or Italic. We can also set typeface as Normal, Sans, Serif or Monospace. The Output will look like
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
Retweet
Tags: android, code, example, font, how to, source, textsize, Textview, typeface Comments (0)
By using the android:background=#ff23cf piece of code the textview background will be filled with #ff23cf color. The output will look like
Retweet
Tags: android, background, color, example, how to, Textview Comments (0)
Now we set the alignment to center so that textview text will appear in the center of the textview(see the below image).
We can set the gravity as top, right, left, bottom,etcyou can also set more than one gravity at a time. For instance, android:gravity=right|center
Retweet
Tags: aligment, aligment center, aligment center text, android, center, gravity, set, text bottom, text center, text left, text right, Textview Comments (5)
Output
2 android:id="@+id/EditText01" 3 android:layout_width="wrap_content"
Here the Hexadecimal value of the Color we used is #23cf34 android:textColor=#23cf34 By using this single line we can easily set the textcolor to anything we like.
Retweet
Tags: android, android:textColor, bold, Button, color, Edittext, font, hex, hexadecimal, set, size, text, textsize, textstyle, Textview Comments (2)
Textview is a View which we can add to any Layout. How to add TextView in a Layout? To add a textview to a layout, select the layout you need to add (here I have selected LinearLayout01) & then click the Add Button (shown in green color with plus symbol intimating Adds a new element)
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
Now you will get a dialog box from that select textview (see the below image).
After selecting the textview from the dialog your xml file layout will look like the below image. Now see the outline & layout to find the textview on that.
How to edit the properties of your textview? To change your textview id android:id=@+id/TextView To change your textview text android:text=This is my first textview sample application To enable or disable textview android:enabled=false To change your textview width & height android:layout_height=wrap_content android:layout_width=fill_parent To change your textview background android:background=@drawable/icon To change your textview text size android:textSize=16px To change your textview text style android:textStyle=bold Now your XMl code looks like
view source print?
01 <?xml version="1.0" encoding="utf-8"?> 02 <LinearLayout android:id="@+id/LinearLayout01" 03 android:layout_width="fill_parent" 04 android:layout_height="fill_parent" 05 xmlns:android="http://schemas.android.com/apk/res/android"> 06 <TextView android:text="This is my first textview sample application" 07 android:id="@+id/TextView"
You can download the sample textview application here Note: If the image is not visible clearly, please right click the image & click on view image. You should then be able to see the image clearly.
Retweet
Tags: android, background, enabled, height, hide, id, image, Layout, linearlayout, properties, remove, size, style, text, textsize, textstyle, Textview, Tutorial, view, visible, wi
Time Picker.
Android Time Picker Dialog Example
February 1, 2010 in Android Tutorial, Dialog, Time Picker by Sasikumar In Android, we can display Time Picker in the dialog box itself. Here is an example to show how to display the time picker in the dialog box in order to get the time.
19 public void onTimeSet(TimePicker view, int hourOfDay, int minute) { 20 Toast.makeText(ExampleApp.this, "Time is="+hourOfDay+":"+minute, Toast.LENGTH_SHORT).show();
21 } 22 }; 23 @Override 24 protected Dialog onCreateDialog(int id) { 25 switch (id) { 26 case TIME_DIALOG_ID: 27 return new TimePickerDialog(this,mTimeSetListener, 0, 0, false); 28 } 29 return null; 30 } 31 }
Retweet
Video.
Android install SDK on Eclipse
June 14, 2010 in Android Tutorial, Tutorial, Video by S.Janardhanan Install Android SDK on eclipse
Retweet
12 </LinearLayout>
Java File
view source print?
01 public class VideoPlayerController extends Activity { 02 03 04 05 06 07 08 09 10 11 VideoView videoView = (VideoView) findViewById(R.id.VideoView); MediaController mediaController = new MediaController(this); mediaController.setAnchorView(videoView); setContentView(R.layout.video); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
12 // Set video link (mp4 format ) 13 14 15 16 17 18 19 } } Uri video = Uri.parse("mp4 video link"); videoView.setMediaController(mediaController); videoView.setVideoURI(video); videoView.start();
Try this!..
0diggsdigg 1
The simple android custom listview can assist only a single string, where its not possible to use them on all application. This leads to create custom list view example tutorial . Step 1: Add a normal listview in the main.xml layout and make sure u set the layout width as fill parent. Main.xml
view source print?
01 <?xml version="1.0" encoding="utf-8"?> 02 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 03 android:orientation="vertical" android:layout_width="fill_parent" 04 android:layout_height="fill_parent"> 05 <TextView android:id="@+id/TextView01" android:layout_height="wrap_content" android:text="List of Country & their denotation" android:textStyle="normal|bold" 06 android:gravity="center_vertical|center_horizontal" android:layout_width="fill_parent"></TextView> 07 <ListView android:id="@+id/ListView01" android:layout_height="wrap_content" 08 android:layout_width="fill_parent"> 09 </ListView> 10 </LinearLayout>
Step 2 : Add two textview(textview1&textview2) in listview.xml and add background image(bg.png) to textview1. Listview.xml
view source A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
print?
01 <?xml version="1.0" encoding="utf-8"?> 02 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 03 android:layout_height="wrap_content" android:gravity="left|center" 04 android:layout_width="wrap_content" android:paddingBottom="5px" 05 android:paddingTop="5px" android:paddingLeft="5px"> 06 <TextView android:id="@+id/TextView01" android:layout_width="wrap_content" 07 android:layout_height="wrap_content" android:gravity="center" 08 android:background="@drawable/bg" android:textColor="#FFFF00" 09 android:text="hi"></TextView> 10 <TextView android:text="@+id/TextView02" android:id="@+id/TextView02" 11 android:layout_width="wrap_content" android:layout_height="wrap_content" 12 android:layout_marginLeft="10px" android:textColor="#0099CC"></TextView> 13 </LinearLayout>
Step 3 : The class EfficientAdapter should extend BaseAdapter for basic listview. Step 4: Create a class Holder that contains two textview. Step 5: Create two separate variables for country list and denotation. Step 6: Set the content view to main and set the set the listview adapter to EfficientAdapter class. This will load the listcontent in the listview.
view source print?
01 import android.app.Activity; 02 import android.os.Bundle; 03 04 import android.content.Context;
05 import android.view.LayoutInflater; 06 import android.view.View; 07 import android.view.ViewGroup; 08 import android.widget.BaseAdapter; 09 import android.widget.ListView; 10 import android.widget.TextView; 11 12 public class customlistview extends Activity { 13 14 private static class EfficientAdapter extends BaseAdapter { 15 private LayoutInflater mInflater; 16 17 public EfficientAdapter(Context context) { 18 mInflater = LayoutInflater.from(context); 19 20 } 21 22 public int getCount() { 23 return country.length; 24 } 25 26 public Object getItem(int position) { 27 return position; 28 } 29
30 public long getItemId(int position) { 31 return position; 32 } 33 34 public View getView(int position, View convertView, ViewGroup parent) { 35 ViewHolder holder; 36 if (convertView == null) { 37 convertView = mInflater.inflate(R.layout.listview, null); 38 holder = new ViewHolder(); 39 holder.text = (TextView) convertView 40 .findViewById(R.id.TextView01); 41 holder.text2 = (TextView) convertView 42 .findViewById(R.id.TextView02); 43 44 convertView.setTag(holder); 45 } else { 46 holder = (ViewHolder) convertView.getTag(); 47 } 48 49 holder.text.setText(curr[position]); 50 holder.text2.setText(country[position]); 51 52 return convertView; 53 } 54
55 static class ViewHolder { 56 TextView text; 57 TextView text2; 58 } 59 } 60 61 @Override 62 public void onCreate(Bundle savedInstanceState) { 63 super.onCreate(savedInstanceState); 64 setContentView(R.layout.main); 65 ListView l1 = (ListView) findViewById(R.id.ListView01); 66 l1.setAdapter(new EfficientAdapter(this)); 67 } 68 69 private static final String[] country = { "Iceland", "India", "Indonesia", 70 "Iran", "Iraq", "Ireland", "Israel", "Italy", "Laos", "Latvia", 71 "Lebanon", "Lesotho ", "Liberia", "Libya", "Lithuania", 72 "Luxembourg" }; 73 private static final String[] curr = { "ISK", "INR", "IDR", "IRR", "IQD", 74 "EUR", "ILS", "EUR", "LAK", "LVL", "LBP", "LSL ", "LRD", "LYD", 75 "LTL ", "EUR" 76 77 }; 78 79 }
Moving ahead from first part Custom List view, we are going to discuss three things. 1.Adding background colors to Listview 2.Adding different Divider color. 3.Triggering action on listview click. Step 1:
Listview Background Color
Adding Custom Background color to listview . For an elegance look for an application the listview color play a key role.
convertView.setBackgroundColor((position & 1) == 1 ? Color.WHITE : Color.LTGRAY);
Note: You will lose item focus upon adding this background color. Step 2 :
Adding divider color.
When you apply a white background to list cell. You need to have change the divider color since it gets hidden by the background color. To change the background color
ColorDrawable divcolor = new ColorDrawable(Color.DKGRAY); l1.setDivider(divcolor); l1.setDividerHeight(2);
Step 3:
Listview Click action
We have to use OnItemClickListener to perform a action when an item on listview is clicked. Upon clicking get the current position of the item on the listview then later its passed to the arraylist to get the country name that was clicked.
l1.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Toast.makeText(getBaseContext(), "You clciked "+country[arg2], Toast.LENGTH_LONG).show(); }
6 Retweet
0diggsdigg
Moving ahead from simple HTML View, Here we are going to see how to place a link inside a HTML Content using TextView. A simple example for how to use links in textview.
8 </LinearLayout>
01 import android.app.Activity; 02 import android.os.Bundle; 03 import android.text.Html; 04 import android.text.method.LinkMovementMethod; 05 import android.widget.TextView; 06 07 public class ExampleApp extends Activity { 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 } } TextView textView = (TextView) findViewById(R.id.TextView01); textView.setText(Html.fromHtml(source)); // Used to enable links in textview. textView.setMovementMethod(LinkMovementMethod.getInstance()); String source = "<b><font color=#ff0000> Html View using TextView" + "</font></b><br><br><a href='http://www.AndroidPeople.com'>AndroidPeople.com</a>" + "<br><br><a href='http://www.Android.com'>Android.com</a>"; setContentView(R.layout.test); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
ToggleButton.
Android ToggleButton
January 21, 2010 in Android Tutorial, ToggleButton by Sasikumar Android Toggle Button is used to set the button as checked or unchecked. We can set this toggle button to Yes or No also. We can change the toggle button text when the stage changes. We can set text for both On stage (ex: YES) & Off stage (ex: NO). Default Text of ON Stage is ON & OFF Stage is OFF. You can change the text through android:textOff & android:textOn property. Your XML code should look like
view source print?
01 <?xml version="1.0" encoding="utf-8"?> 02 <LinearLayout android:id="@+id/LinearLayout01" 03 android:layout_width="fill_parent" 04 android:layout_height="fill_parent" 05 xmlns:android="http://schemas.android.com/apk/res/android" 06 android:gravity="center"> 07 <ToggleButton android:id="@+id/ToggleButton01" 08 android:layout_width="wrap_content" 09 android:layout_height="wrap_content" 10 android:textOff="Off Stage" 11 android:textOn="On Stage"/> 12 </LinearLayout>
Retweet
TTS.
Android TTS (Text To Speech) Example
April 12, 2010 in Android Tutorial, TTS by Sasikumar In android,we can able to make text as speech using TTS. TTS supports English, French, German, Italian and Spanish Languages. TTS Example :view source print?
01 public class TTSExample extends Activity implements OnInitListener { 02 03 04 05 06 @Override public void onCreate(Bundle savedInstanceState) { /** Called when the activity is first created. */ private TextToSpeech tts;
07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 } } }
super.onCreate(savedInstanceState); setContentView(R.layout.main);
Intent checkIntent = new Intent(); checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA); startActivityForResult(checkIntent, 0); tts = new TextToSpeech(this, this);
@Override public void onInit(int arg0) { // TODO Auto-generated method stub String speech1 = "How are you?"; String speech2 = "I hope you are fine."; tts.setLanguage(Locale.US); tts.speak(speech1, TextToSpeech.QUEUE_FLUSH, null); tts.speak(speech2, TextToSpeech.QUEUE_ADD, null);
To change the language use tts.setLangauge(); To make text to speak use tts.speak(); By suing these simple example you can able to use TTS.
digg
Moving ahead from Android XML Parsing using SAXParser, here we are going to see about how to parse a XML using DOM Parser. we are going to parse XML from net ( by passing URL ) not from local file or string. The output looks similar to
example.xml ( http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml )
view source print?
01 <maintag>
02 03 04 05 06 07 08 09
<item> <name>AndroidPeople</name> <website category="android">www.androidpeople.com</website> </item> <item> <name>iPhoneAppDeveloper</name> <website category="iPhone">www.iphone-app-developer.com</website> </item>
10 </maintag>
XMLParsingDOMExample.java This is main activity class. when App. starts this file will be called first. This file contains how to use DOM Parser to handle XML tags.
view source print?
01 package com.androidpeople.xml.parsing; 02 03 import java.net.URL; 04 05 import javax.xml.parsers.DocumentBuilder; 06 import javax.xml.parsers.DocumentBuilderFactory; 07 08 import org.w3c.dom.Document; 09 import org.w3c.dom.Element; 10 import org.w3c.dom.Node; 11 import org.w3c.dom.NodeList;
12 import org.xml.sax.InputSource; 13 14 import android.app.Activity; 15 import android.os.Bundle; 16 import android.widget.LinearLayout; 17 import android.widget.TextView; 18 19 public class XMLParsingDOMExample extends Activity { 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 URL url = new URL( try { /** Create a new textview array to display the results */ TextView name[]; TextView website[]; TextView category[]; /** Create a new layout to display the view */ LinearLayout layout = new LinearLayout(this); layout.setOrientation(1); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
"http://www.androidpeople.com/wpcontent/uploads/2010/06/example.xml"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new InputSource(url.openStream())); doc.getDocumentElement().normalize();
/** Assign textview array lenght by arraylist size */ name = new TextView[nodeList.getLength()]; website = new TextView[nodeList.getLength()]; category = new TextView[nodeList.getLength()];
Element fstElmnt = (Element) node; NodeList nameList = fstElmnt.getElementsByTagName("name"); Element nameElement = (Element) nameList.item(0); nameList = nameElement.getChildNodes();
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 } } }
NodeList websiteList = fstElmnt.getElementsByTagName("website"); Element websiteElement = (Element) websiteList.item(0); websiteList = websiteElement.getChildNodes(); website[i].setText("Website = " + ((Node) websiteList.item(0)).getNodeValue());
87 }
0diggsdigg
Android XML Parsing Tutorial Using DOMParser Here we are going to see about how to parse a XML using SAX Parser. we are going to parse XML from net not from local file.
Files Used:XMLParsingExample.java ( Main Activity ) SitesList.java ( Getter & Setter Method ) MyXMLHandler.java ( XML Handling ) example.xml ( XML file from net )
example.xml ( http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml )
view source print?
01 <maintag> 02 03 04 05 06 07 <item> <name>AndroidPeople</name> <website category="android">www.androidpeople.com</website> </item> <item> <name>iPhoneAppDeveloper</name>
08 09
10 </maintag>
If tag names are different, then we can use string to set & get the value. But here item,name & website tags are repeating 2 times. So we can use ArrayList to store & get the data.
XMLParsingExample.java
This is main activity class. when App. starts this file will be called first. This file contains how to use SAX Parser to handle XML tags.
13 public class XMLParsingExample extends Activity { 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 /** Handling XML */ SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); try { /** Create a new textview array to display the results */ TextView name[]; TextView website[]; TextView category[]; /** Create a new layout to display the view */ LinearLayout layout = new LinearLayout(this); layout.setOrientation(1); /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); /** Create Object For SiteList Class */ SitesList sitesList = null;
38 39 40 41 42
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */ URL sourceUrl = new URL( "http://www.androidpeople.com/wpcontent/uploads/2010/06/example.xml");
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 /** Set the result text in textview and add it to layout */ for (int i = 0; i < sitesList.getName().size(); i++) { /** Assign textview array lenght by arraylist size */ name = new TextView[sitesList.getName().size()]; website = new TextView[sitesList.getName().size()]; category = new TextView[sitesList.getName().size()]; /** Get result from MyXMLHandler SitlesList Object */ sitesList = MyXMLHandler.sitesList; } } catch (Exception e) { System.out.println("XML Pasing Excpetion = " + e); /** Create handler to handle XML Tags ( extends DefaultHandler ) */ MyXMLHandler myXMLHandler = new MyXMLHandler(); xr.setContentHandler(myXMLHandler); xr.parse(new InputSource(sourceUrl.openStream()));
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 } } }
name[i] = new TextView(this); name[i].setText("Name = "+sitesList.getName().get(i)); website[i] = new TextView(this); website[i].setText("Website = "+sitesList.getWebsite().get(i)); category[i] = new TextView(this); category[i].setText("Website Category = "+sitesList.getCategory().get(i));
MyXMLHandler.java
This file is used to handle the XML tags. So we need to extends with DefaultHandler. we need to override startElement, endElement & characters method . startElemnt method called when the tag starts. endElemnt method called when the tag ends characres method to get characters inside tag.
01 package com.androidpeople.xml.parsing; 02 03 import org.xml.sax.Attributes; 04 import org.xml.sax.SAXException; 05 import org.xml.sax.helpers.DefaultHandler; 06 07 public class MyXMLHandler extends DefaultHandler { 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 /** Called when tag starts ( ex:- <name>AndroidPeople</name> * -- <name> )*/ @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { } public static void setSitesList(SitesList sitesList) { MyXMLHandler.sitesList = sitesList; } public static SitesList getSitesList() { return sitesList; Boolean currentElement = false; String currentValue = null; public static SitesList sitesList = null;
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 /** set value */ if (localName.equalsIgnoreCase("name")) currentElement = false; /** Called when tag closing ( ex:- <name>AndroidPeople</name> * -- </name> )*/ @Override public void endElement(String uri, String localName, String qName) throws SAXException { } } if (localName.equals("maintag")) { /** Start */ sitesList = new SitesList(); } else if (localName.equals("website")) { /** Get attribute value */ String attr = attributes.getValue("category"); sitesList.setCategory(attr); currentElement = true;
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 } } } }
/** Called to get tag characters ( ex:- <name>AndroidPeople</name> * -- to get AndroidPeople Character ) */ @Override public void characters(char[] ch, int start, int length) throws SAXException {
SitesList.java
print?
01 package com.androidpeople.xml.parsing; 02 03 import java.util.ArrayList; 04 05 /** Contains getter and setter method for varialbles 06 public class SitesList { 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 public ArrayList<String> getWebsite() { } public void setName(String name) { this.name.add(name); } public ArrayList<String> getName() { return name; /** In Setter method default it will return arraylist * change that to add */ /** Variables */ private ArrayList<String> name = new ArrayList<String>(); private ArrayList<String> website = new ArrayList<String>(); private ArrayList<String> category = new ArrayList<String>(); */
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 } } } } }
return website;
Thats it.
0diggsdigg
In android, we can able to post a status to twitter by using jtwitter. Its very simple to post a status in twitter. For that we need jtwitter.jar. you can download the jwitter.jar from here Post Status in Twitter Example :Create a new android project, Add the below code in your AndroidManifest.xml for internet permission
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
Now we need to add Jtwitter to our project. Download the jwitter and save it in local drive. Click the Android Project > Properties > (In left Pane) Java Build Path > Libraries In Libraries Tab click the Add External Jars Button and then add the Jtwitter jar file.
04 import winterwell.jtwitter.TwitterException; 05 import android.app.Activity; 06 import android.os.Bundle; 07 import android.widget.Toast; 08 09 public class TwitterExample extends Activity { 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 try { //Status to post in Twitter twitter.setStatus("This is my first Tweet from Android AndroidPeople.com"); Toast.makeText(TwitterExample.this, "Article Posted to Twitter Successfully!!", Toast.LENGTH_SHORT).show(); } catch(TwitterException.E401 e) // Set your Twitter username / Password twitter = new Twitter("username","password"); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Twitter twitter;
25 26 27
28 29 30 31 32 33 34 35 36 37 } }
{ // comes here when username or password is wrongs Toast.makeText(TwitterExample.this, "Wrong Username or Password,Kindly Check your logins",Toast.LENGTH_SHORT).show(); } catch(Exception e) { Toast.makeText(TwitterExample.this, "Network Host not responding",Toast.LENGTH_SHORT).show(); }
You can download the full source code here Android Facebook API example using FBRocket