Saturday, 21 December 2013

Android File Handling

Lets learn File handling in Android.

First, create a layout to enter and save the data and to display the saved data.

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <EditText 
        android:id="@+id/et"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="Enter Here"
        />
    
    <TextView
        android:id="@+id/tv"
        android:layout_below="@+id/et"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <Button
        android:id="@+id/read"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/save"
        android:layout_alignBottom="@+id/save"
        android:layout_toRightOf="@+id/save"
        android:text="READ" />

    <Button
        android:id="@+id/save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/tv"
        android:layout_centerVertical="true"
        android:text="SAVE" />

</RelativeLayout>



And then make changes in the MainActivity.java.

package com.codingredefined.androidfilehandling;

import java.io.FileInputStream;
import java.io.FileOutputStream;

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

public class MainActivity extends Activity
{
Button b1,b2;
EditText et;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.save);
b2=(Button)findViewById(R.id.read);
et=(EditText)findViewById(R.id.et);
tv=(TextView)findViewById(R.id.tv);
b1.setOnClickListener(new View.OnClickListener()
{

@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
String str=et.getText().toString();
FileOutputStream fos;
try
{
fos=openFileOutput("abc",Context.MODE_PRIVATE);
fos.write(str.getBytes());
fos.close();
Toast.makeText(MainActivity.this,"Data Saved",Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
Toast.makeText(MainActivity.this,"Data NOT Saved",Toast.LENGTH_SHORT).show();
}
}
});
b2.setOnClickListener(new View.OnClickListener()
{

@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
FileInputStream fis;
try
{
fis=openFileInput("abc");
int i=0;
String str="";
while((i=fis.read())!=-1)
{
str=str+((char)+i);
}
tv.setText(str);
fis.close();
}
catch(Exception e)
{
Toast.makeText(MainActivity.this,"Data NOT Read",Toast.LENGTH_SHORT).show();
}
}
});
}

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

}


The following output is obtained.




Friday, 20 December 2013

Android Notification

Learn to create Notification.

Open the project folder and create a new folder "raw" in the res folder. Put a .mp3 file which you want to use as notification sound.

Do the following coding in the MainActivity.java file.

package com.codingredefined.notification;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;

public class MainActivity extends Activity 
{
private static final int HELLO_ID=1;
MediaPlayer mMediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String ns=Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager=(NotificationManager)getSystemService(ns);
int icon=R.drawable.ic_launcher;
CharSequence tickerText="Hello!";
long when=System.currentTimeMillis();
Notification notification=new Notification(icon, tickerText, when);
//Vibrate on Notification
notification.defaults=Notification.DEFAULT_VIBRATE;
long[] vibrate={0,100,200,300};
notification.vibrate=vibrate;
//Glow LED
notification.defaults=Notification.DEFAULT_LIGHTS;
notification.ledARGB=0xff00ff00;
notification.ledOnMS=300;
notification.ledOffMS=1000;
notification.flags=Notification.FLAG_SHOW_LIGHTS;
//Activate notification
Context context=getApplicationContext();
CharSequence contextTitle="My Notification";
CharSequence contextText="Hello World!!!";
Intent notificationIntent=new Intent(this,MainActivity1.class);
PendingIntent contentIntent=PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contextTitle, contextText, contentIntent);
mNotificationManager.notify(HELLO_ID, notification);
//Sound
mNotificationManager.notify(HELLO_ID, notification);
mMediaPlayer=new MediaPlayer();
mMediaPlayer=MediaPlayer.create(this,R.raw.abc);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setLooping(true);
mMediaPlayer.start();
Thread t=new Thread()
{
@Override
public void run()
{
try
{
Thread.sleep(5000);
}
catch(Exception e){}
mMediaPlayer.stop();
}
};
t.start();
}

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

}


The following output will be obtained.

Tuesday, 10 December 2013

Web View

WebView is a view which can display web pages in your activity.

Create a webview in layout file.

<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="200dp" />

The button created in the below image is of no use.


Make the changes in the Activity file.

package com.codingredefined.webview;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFeatureInt(Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
WebView mywebView;
mywebView=(WebView)findViewById(R.id.webview);
mywebView.getSettings().setJavaScriptEnabled(true);
mywebView.loadUrl("http://www.google.com");
mywebView.setWebViewClient(new WebViewClient());
mywebView.setInitialScale(1);
mywebView.getSettings().setUseWideViewPort(true);
final Activity MyActivity=this;
mywebView.setWebChromeClient(new WebChromeClient()
{
public void onProgressChanged(WebView view,int progress)
{
MyActivity.setTitle("Loading...");
MyActivity.setProgress(progress*100);
if(progress==100)
{
MyActivity.setTitle("WebView");
}
}
});
}

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

}



This will be the output.


Friday, 6 December 2013

Progress Bar

Now these are the steps to create a Progress Bar in your app...

Create a Button and a Progress Bar in main layout file.

<TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Progress Bar" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="60dp"
        android:onClick="startProgress"
        android:text="Start Progress Bar" />

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="30dp"
        android:indeterminate="false"
        android:max="10"
        android:padding="4dp" />


Code your activity file.

package com.codingredefined.progressbar;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.ProgressBar;

public class MainActivity extends Activity
{
private Handler handler;
private ProgressBar progress;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progress=(ProgressBar)findViewById(R.id.progressBar1);
handler=new Handler();
}

public void startProgress(View view)
{
Runnable runnable=new Runnable()
{
@Override
public void run()
{
for(int i=0;i<=10;i++)
{
final int value=i;
try
{
Thread.sleep(1500);
}
catch(Exception e)
{}
handler.post(new Runnable()
{
@Override
public void run()
{
progress.setProgress(value);
}
});
}
}
};
new Thread(runnable).start();
}

}



The following output will be obtained.


Custom Dialog

So here we are with a simple method to create a own designed dialog box.

Create a button to activate the dialog box.

<TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Click Button"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/buttonShowCustomDialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:text="Button" />


Now create a new layout file named "custom_dialog.xml" to design your dialog box.

<ImageView
    android:id="@+id/image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginRight="5dp"
    />

<TextView
    android:id="@+id/text"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="#DC143C"
    android:layout_toRightOf="@+id/image"
    />
   
<Button
    android:id="@+id/dialogButtonOK"
    android:layout_width="100px"
    android:layout_height="wrap_content"
    android:text="OK"
    android:layout_marginTop="5dp"
    android:layout_marginRight="5dp"
    android:layout_below="@+id/image"
    />


Now make changes in the main activity file.

package com.codingredefined.customdialog;

import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity
{
Button button;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
button=(Button)findViewById(R.id.buttonShowCustomDialog);
button.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
final Dialog dialog=new Dialog(context);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Custom Dialog");
TextView text=(TextView)dialog.findViewById(R.id.text);
text.setText("Android Custom Dialog");
ImageView image=(ImageView)dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.ic_launcher);
Button dialogButton=(Button)dialog.findViewById(R.id.dialogButtonOK);
dialogButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
dialog.dismiss();
}
});
dialog.show();
}
});
}

}


Following output will be obtained.



Tuesday, 3 December 2013

Hyperlink in a Text View

Now we will learn to embed Hyperlinks in a TextView.

First make a text view in the layout file.

<TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/link1" />


Now open the "strings.xml" file under the "values" folder. And add the following code to it.

<string name="link1"><![CDATA[This is Link to <a href="http://www.google.com/">Google</a>]]></string>


Finally make changes in the activity file.

package com.codingredefined.linkinatextview;

import android.os.Bundle;
import android.app.Activity;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity
{

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

TextView tv=(TextView)findViewById(R.id.tv);
tv.setText(Html.fromHtml(getString(R.string.link1)));
Linkify.addLinks(tv, Linkify.ALL);
tv.setMovementMethod(LinkMovementMethod.getInstance());
}

}


The following output will be obtained.


Clicking on Google will automatically open google.com in your default browser.

Custom Toast

So back to blogging after a long time with a lot new stuff.

This time we are making a CUSTOM toast designed completely by you.
This is what will appear as a toast when you will click the button.


First create a button in the native layout file to trigger the toast.

<Button
        android:id="@+id/buttonShow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:text="Show Custom Toast" />


After that create a new layout file in the same folder named "custom_toast.xml". And create an image view and a text view in that layout file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toast_layout_root"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 
    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_marginRight="10dp"
        />
 
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:textColor="#DC143C"
        />

</RelativeLayout>


Now the final step is to make changes in the activity file.

package com.codingredefined.customtoast;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity
{
Button button;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.buttonShow);
button.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
LayoutInflater inflater=getLayoutInflater();
View layout=inflater.inflate(R.layout.custom_toast,(ViewGroup)findViewById(R.id.toast_layout_root));
ImageView image=(ImageView)layout.findViewById(R.id.image);
image.setImageResource(R.raw.reebok);
TextView text=(TextView)layout.findViewById(R.id.text);
Toast toast=new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
});
}

}


The following output should be observed.


Saturday, 12 October 2013

Android Progress Dialog

In this exercise we will learn to create a Progress Dialog.

Lets create a button to trigger the progress dialog.

<Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Start" />


Now to trigger the progress dialog

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

public class MainActivity extends Activity
{
Button st;
ProgressDialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
st=(Button)findViewById(R.id.button1);
st.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
dialog=ProgressDialog.show(MainActivity.this,"Progress Dialog","Loading...",true);
Thread t=new Thread()
{
public void run()
{
try
{
Thread.sleep(5000);
dialog.cancel();
}
catch(Exception e)
{
Toast.makeText(MainActivity.this,""+e,Toast.LENGTH_LONG).show();
}
}
};
t.start();
}
});
}
}


The program has been coded to show the progress dialog for 5 seconds.


Sunday, 6 October 2013

Radio Button Alert Box

In this post, we will create a Alert Box with radio Buttons.

Lets create a button which will trigger the alert box.

<Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Click Me" />


After creating the button, make changes in the java file.

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity
{
Button b;
final CharSequence[] items={"Red","Green","Blue"};
AlertDialog.Builder builder;
AlertDialog alert;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b=(Button)findViewById(R.id.button1);
builder=new AlertDialog.Builder(this);
builder.setTitle("Pick a Color");
builder.setSingleChoiceItems(items,-1,new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this,"Color : "+items[which],Toast.LENGTH_LONG).show();
}
});
alert=builder.create();
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
alert.show();
}
});
}

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

}


Output should look like



Friday, 4 October 2013

Button Alert Box

Now lets start with the Button Alert Box.
To start create a button on whose click the alert box would appear.

<Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:text="Click Me...!!!"  />


Now to make the alert box appear on click of the button and illustrate working of Button Alert Box.

public class MainActivity extends Activity
{
Button b;
AlertDialog alert;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b=(Button)findViewById(R.id.button1);
final CharSequence[] items={"Red","Green","Blue"};
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Pick a Colour.");
builder.setItems(items, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
//TODO Auto-generated method stub
Toast.makeText(MainActivity.this,""+items[which],Toast.LENGTH_SHORT).show();
}
});
alert=builder.create();
b.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
//TODO Auto-generated method stub
alert.show();
}
});
}
}


Now the output should look like this




Sunday, 15 September 2013

Context Menu

Lets create a CONTEXT MENU. This menu appears n screen when you long click an UI component.

To begin you need to make a UI component on whose long click the context menu would appear.

<TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="145dp"
        android:text="Context Menu"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="18dp"
        android:text="Menu which appears on long click"
        android:textAppearance="?android:attr/textAppearanceMedium" />


Then create 2 menu items to be shown in the context menu.

 <item
        android:id="@+id/item1"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="Menu Item 1"/>

    <item
        android:id="@+id/item2"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="Menu Item 2"/>


Now in the onCreate(), you need to register the component for the context menu after getting its reference from the layout file. And then write the code to make the menu working.

package com.codingredefined.androidcontextmenu;

import android.os.Bundle;
import android.app.Activity;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity 
{
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.textView1);
registerForContextMenu(tv);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.main, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item)
{
switch(item.getItemId())
{
case R.id.item1:
Toast.makeText(this, "Menu Item 1 Selected", Toast.LENGTH_LONG).show();
break;
case R.id.item2:
Toast.makeText(this, "Menu Item 2 Selected", Toast.LENGTH_LONG).show();
break;
}
return true;
}
}



After completing the above mentioned steps, your output should look like...