Thursday, March 17, 2011

Displaying Alert Dialog within another Alert Dialog in Android ?

Hi All, Let us know see, how to create an Alert Dialog inside another Alert Dialog?

Step 1: Create a Alert Dialog as i shown below and implement click Listener as i shown below

package com.san.test;

import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MyActivity extends Activity {

/** Called when the activity is first created. */

Context ctx=null;
Button b=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

b=(Button )findViewById(R.id.test1);
ctx=this;
b.setOnClickListener(new android.view.View.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub

displayAlert();

}}

);





}

public void displayAlert()
{

OnClickListener btnOnClick = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {


new AlertDialog.Builder(ctx).setMessage("BUTTON_POSITIVE")
.setTitle("Alert Postive ")
.setCancelable(true)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
finish();
}
})
.show();




} else if(which == DialogInterface.BUTTON_NEGATIVE){
new AlertDialog.Builder(ctx).setMessage("BUTTON_NEGATIVE")
.setTitle("Alert Negative")
.setCancelable(true)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
finish();
}
})
.show();

} else if(which == DialogInterface.BUTTON_NEUTRAL) {
// More Info
new AlertDialog.Builder(ctx).setMessage("BUTTON_NEUTRAL")
.setTitle("Alert Neutral")
.setCancelable(true)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
finish();
}
})
.show();
}
}
};


AlertDialog promptInstall = new AlertDialog.Builder(ctx).setTitle("First Alert")
.setMessage(
"mY First Alert")
.setPositiveButton("OK", btnOnClick).setNegativeButton(
"Cancel", btnOnClick).setNeutralButton("More Info",
btnOnClick).create();

promptInstall.show();
}
}


See the images

Dispalying Toast Message in a Service in Android?

Hi All, Let us how to create Toast Message in Service

 Step 1:  Create a Handler and thread as i shown below

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;

public class MyService extends Service{

String msg="I m Toast";

Thread t = new Thread(){
public void run(){

Message myMessage=new Message();
Bundle resBundle = new Bundle();
resBundle.putString("status", "SUCCESS");
myMessage.obj=resBundle;
handler.sendMessage(myMessage);
}
};



private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Toast.makeText(getApplicationContext(), "msg", Toast.LENGTH_LONG).show();
}
};


@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub

return null;
}

@Override
public void onCreate() {
 t.start();
}


}


Friday, March 11, 2011

Checking Internet Connection and Displaying Alert Dialog Box in Android

Hi Friends, Let us know, how to display Alert Dialog in Android

Step 1: I had checked Alert Message , when the Internet is Disconnected.

  So created a method, which checks the Internet Connection

public boolean netCheck()
{
ConnectivityManager conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

if ( conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED
|| conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED ) {
//notify user you are not online
bs_netcheck =true;

}
return bs_netcheck;
}



Step 2: Create a Method which Shows Alert Dialog as i shown below

public void displayAlert()
{
new AlertDialog.Builder(this).setMessage("Please Check Your Internet Connection and Try Again")
.setTitle("Network Error")
.setCancelable(true)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
finish();
}
})
.show();
}



Step 3: Now Call this method  as i shown below
Boolean  bs_netcheck=false;
bs_netcheck = netCheck();
if(bs_netcheck == true)
{
displayAlert();
}




Friday, March 4, 2011

Adding Gradient Effects to Android Button?

Hi  All, Let us How to add gradient effects to default Android Buttons

Step 1: Create a Xml under drawable folder, i had created a XML file called custombutton

<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="true" >
<shape>
<gradient
android:startColor="#ff5500"
android:endColor="#999999"
android:angle="270" />
<stroke
android:width="3dp"
android:color="#999999" />
<corners
android:radius="3dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>

<item android:state_focused="true" >
<shape>
<gradient
android:endColor="#ff5500"
android:startColor="#999999"
android:angle="270" />
<stroke
android:width="3dp"
android:color="#999999" />
<corners
android:radius="3dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>

<item>
<shape
android:shape="rectangle">

<gradient android:type="radial" android:gradientRadius="50"
android:startColor="#999999" android:endColor="#000000" />
<!-- <corners-->
<!-- android:radius="10dp" />-->
<corners android:bottomRightRadius="7dp" android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp" android:topRightRadius="7dp"/>
</shape>
</item>
</selector>

Step2: Apply this to your Button by Just calling this file to the Background  of Button , as i had shown below

<Button android:text=" Back" android:id="@+id/back" android:background="@drawable/custombuttonnew"
android:cursorVisible="true"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_centerVertical="true" />

That's it



Tuesday, March 1, 2011

Login Based Application in Android using SQLite DataBase

Hi , Let us See how to Create a Login Based Application in Android.

My Aim is , i have to display SignUp Page,when the User access my application for the first time,after that i want to display login page and make a check on it.

Step 1: How to Know that the device interacting with my application for first time.
For that, we have to get DeviceId of that Device. With the Help of Telephony Manager it's possible to get the Device Id of a Device.
The code is

String device_id;
TelephonyManager telemngr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
device_id=telemngr.getDeviceId();

Step2:  How to Create DataBase in Android
I had used SQLite Open Browser to create my database file in assets folder of my project. I had created a table namely login_details with fileds such as username and password and confpassword and deviceid. To Download SQLite Open Browser, pls click this link  http://sourceforge.net/projects/sqlitebrowser/

Step 3: Create a Class which is extends from SQLiteOpenHelper, this is the class which help us to create and mange database. A Sample Code Snippet of this Class

public class MyDBHelper extends SQLiteOpenHelper{
//Declaring Local Variables for database name , and database path and sqlite object and my context
private static String DB_PATH = "";
private static final String DB_NAME = "frnd.db"; // i had created this in my assets folder
private SQLiteDatabase myDataBase;
private final Context myContext;
private static MyDBHelper mDBConnection;
static int version_val=1; // version of my table

//Constructor which sends db name to SQLiteOpenHelper
public MyDBHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
this.myContext = context;
DB_PATH = "/data/data/"
+ context.getApplicationContext().getPackageName()
+ "/databases/";
}

// Used to get the Object

public static synchronized MyDBHelper getDBAdapterInstance(Context context) {
if (mDBConnection == null) {
mDBConnection = new MyDBHelper(context,DB_NAME,null,version_val);
}
return mDBConnection;
}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub

}

public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
} else {

// By calling following method
// 1) an empty database will be created into the default system path of your application
// 2) than we overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}

private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
Log.d("MyPath",myPath);
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);

} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}

private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}

public void openDataBase() throws SQLException {
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}

@Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}


public ArrayList<ArrayList<String>> selectRecordsFromDBList(String query, String[] selectionArgs) {
ArrayList<ArrayList<String>> retList = new ArrayList<ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
Cursor cursor = myDataBase.rawQuery(query, selectionArgs);
if (cursor.moveToFirst()) {
do {
list = new ArrayList<String>();
for(int i=0; i<cursor.getColumnCount(); i++){
list.add( cursor.getString(i) );
}
retList.add(list);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return retList;
}


public long insertRecordsInDB(String tableName, String nullColumnHack,
ContentValues initialValues) {
return myDataBase.insert(tableName, nullColumnHack, initialValues);
}

public int deleteRecordInDB(String tableName, String whereClause,
String[] device_id) {
return myDataBase.delete(tableName, whereClause, device_id);
}
}

 Step 4: Creating a Class which helps me to Store my database values in a Variables

public class StoreValue {

String dev_id="";
String username="";
String password="";

public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDev_id() {
return dev_id;
}
public void setDev_id(String dev_id) {
this.dev_id = dev_id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}


}


Step5: Now i had created an Activity, which retervies the device id from my table, here what i had did, if the deviceid from the table matches with my the deviceid of current device which is given  by telephony manager,then i call Login Page instead of SignUp page.

Now cerating my Object for StoreVal class ,declare it and intiallize it

public class MyActivity extends Activity {

Intent Loginjump;
static String device_id;
String default_deviceid=null;
static int version_val=1;
private static final String DB_NAME = "frnd.db";
private ArrayList<StoreValue> mydata=null;
int i=0;
boolean mymatch=false;

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

MyDBHelper db = new MyDBHelper(getApplicationContext(),DB_NAME,null,version_val);

Log.d("Flow Starts ","0");

TelephonyManager telemngr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
device_id=telemngr.getDeviceId();

mydata= getDeviceID(); // initialize the Object of StoreValue Class

Log.d("MyData Size",Integer.toString(mydata.size()));
for(i=0;i<mydata.size();i++)
{
System.out.println("Mydata of i"+(mydata.get(i).getDev_id()));
Log.d("My Device Id",device_id);
if(mydata.get(i).getDev_id().equals(device_id))
{
mymatch=true;
Log.d("MY Data ",mydata.get(i).toString());
Log.d("Device _ id",device_id);
break;
}


}

if(mymatch == true)
{
Loginjump= new Intent(MyActivity.this,LoginActivity.class);
startActivity(Loginjump);
}

else
{
Loginjump= new Intent(MyActivity.this,Sign.class);
startActivity(Loginjump);


}

}

public ArrayList<StoreValue> getDeviceID(){

MyDBHelper dbAdapter=MyDBHelper.getDBAdapterInstance(this);
try {
dbAdapter.createDataBase();
} catch (IOException e) {
Log.i("*** select ",e.getMessage());
}
dbAdapter.openDataBase();
String query="SELECT deviceid FROM login_details;";
ArrayList<ArrayList<String>> stringList = dbAdapter.selectRecordsFromDBList(query, null);
dbAdapter.close();

ArrayList<StoreValue> usersList = new ArrayList<StoreValue>();
for (int i = 0; i < stringList.size(); i++) {
ArrayList<String> list = stringList.get(i);
StoreValue user = new StoreValue();
try {
user.dev_id = list.get(0);
   
} catch (Exception e) {
Log.i("***" + MyActivity.class.toString(), e.getMessage());
}
usersList.add(user);
}
return usersList;
}

}

Step 6: If the Boolean Variable mymatch retruns false,means that's the device id of this device is not in database,at that time we have to call SignUp page and store the username and password and confpassword and deviceid in our login_details table. The Sample Code Sinnpet

public class Sign extends Activity {
EditText u_name=null,pwd=null,confpwd=null;
Button mysign_submit;
String username="",password="",confpassword="";
static Context c;
Intent Loginjump;

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

u_name=(EditText)findViewById(R.id.userval);
pwd=(EditText)findViewById(R.id.mypwdval);
confpwd=(EditText)findViewById(R.id.myconfpwdval);
mysign_submit=(Button)findViewById(R.id.mysubmit);

c= this;

mysign_submit.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("I am fired","ok");
username=u_name.getText().toString();
password=pwd.getText().toString();
confpassword=confpwd.getText().toString();

//if(UserName)
Log.d("UserName",username);
Log.d("Password",password);
Log.d("ConfPassword",confpassword);

if(password != confpassword)
{
displayAlert();
}

MyDBHelper dbAdapter = MyDBHelper.getDBAdapterInstance(Sign.this);
dbAdapter.openDataBase();

ContentValues initialValues = new ContentValues();

initialValues.put("username", username);
initialValues.put("password",password);
initialValues.put("confpassword",confpassword);
initialValues.put("deviceid", MyActivity.device_id);

long n = dbAdapter.insertRecordsInDB("login_details", null, initialValues);
Toast.makeText(Sign.this, "new row inserted with id = "+n, Toast.LENGTH_SHORT).show();
if(n>0)
{
Loginjump= new Intent(Sign.this,MyProfile.class);
startActivity(Loginjump);
}
}
}); 
}
public static void displayAlert()
{
new AlertDialog.Builder(c).setMessage(" Your Password and Confrim Password are not Same ")
.setTitle("Password Alert")
.setCancelable(true)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
System.exit(0);
}
})
.show();
}
}

Step 7:  If the Boolean Variable mymatch retruns true,means that's the device id of this device is  in database,so we have to call Login page and reterives the username and password and check that username and password.

public class LoginActivity extends Activity{
EditText u_name=null,pwd=null;
Button mylogin_submit;
String username="",password="";
private ArrayList<StoreValue> mydata=null;
int i=0;
Intent Loginjump;
static Context c;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.logingui);
u_name=(EditText)findViewById(R.id.userval);
pwd=(EditText)findViewById(R.id.mypwdval);
mylogin_submit = (Button)findViewById(R.id.submit);
c= this;

mylogin_submit.setOnTouchListener(new OnTouchListener (){
@Override public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
username=u_name.getText().toString();
Log.d("UserName",username);
password=pwd.getText().toString();
mydata=getValue();
Log.d("MyData Size",Integer.toString(mydata.size()));
for(i=0;i<mydata.size();i++)
{
System.out.println("Mydata of i"+(mydata.get(0).username));

if(mydata.get(i).getPassword().equals(password) && mydata.get(i).getUsername().equals(username))
{

Log.d("Success","Boss");
Loginjump= new Intent(LoginActivity.this,MyProfile.class);
startActivity(Loginjump);

}
else
{
Log.d("Failure","1");
displayAlert();
}
}
return false;
}});
}

public static void displayAlert()
{
new AlertDialog.Builder(c).setMessage(" Your Password and Confrim Password are not Same ")
.setTitle("Password Alert")
.setCancelable(true)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
System.exit(0);
}
})
.show();
}

public ArrayList<StoreValue> getValue(){

MyDBHelper dbAdapter=MyDBHelper.getDBAdapterInstance(this);
try {
dbAdapter.createDataBase();
} catch (IOException e) {
Log.i("*** select ",e.getMessage());
}
dbAdapter.openDataBase();
String query="SELECT * FROM login_details;";
ArrayList<ArrayList<String>> stringList = dbAdapter.selectRecordsFromDBList(query, null);
dbAdapter.close();

ArrayList<StoreValue> usersList = new ArrayList<StoreValue>();
for (int i = 0; i < stringList.size(); i++) {
ArrayList<String> list = stringList.get(i);
StoreValue user = new StoreValue();
try {
final StoreValue listItem = mydata.get(i); // --CloneChangeRequired
if (listItem != null) {

user.username = list.get(0);
//Log.d("list.get 0",list.get(0));
System.out.println("List get 0"+list.get(0));

user.password = list.get(1);
System.out.println("List get 1"+list.get(1));
System.out.println("List get 2"+list.get(2));
System.out.println("List get 3"+list.get(3));
// Log.d("list.get 1",list.get(1));
}
} catch (Exception e) {
//Log.i("***" + LoginActivity.class.toString(), e.getMessage());
}
usersList.add(user);
}
return usersList;
}
}







Notification in Android Using AlarmManager, BoradCastReceiver & Services

    Our aim is to show notification message to user in a specific time.     Say For example , I have planned to show Notification ...