Showing posts with label ANDROID. Show all posts
Showing posts with label ANDROID. Show all posts

Sunday, 26 July 2015

Android Check Network Connection

You may be building an application which requires an Internet connection. It is very important to detect the internet connection before the application starts working so that to prevent the application from raising exceptions. Here I am explaining how to achieve the goal.

First you need to include the permissions in the Manifest file after the <application> tag.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


After including the permissions, just add a few lines of code where you want to detect the internet connection.

ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] arrar_ni = cm.getAllNetworkInfo();
        for (NetworkInfo ni : arrar_ni)
        {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
            {
                if (ni.isConnected())
                {
                    Toast.makeText(this, "WiFi Available", Toast.LENGTH_LONG).show();
                } else
                {
                    Toast.makeText(this, "WiFi Not Available", Toast.LENGTH_LONG).show();
                }
            }
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
            {
                if (ni.isConnected())
                {
                    Toast.makeText(this, "Mobile Available", Toast.LENGTH_LONG).show();
                } else
                {
                    Toast.makeText(this, "Mobile Not Available", Toast.LENGTH_LONG).show();
                }
            }
        }



The above code will generate Toast displaying the availability and type of internet connection. You can replace the Toast statements with your code according to the requirement of your application.

Sunday, 15 March 2015

Android Date Picker

So here we are with an example to demonstrate how to implement Date Picker in your Android application.

First we need to create a TextBox to display the date and a button to trigger the Date Picker Dialog Box.

<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="com.codingredefined.datepicker.MainActivity" >

    <TextView
        android:id="@+id/displayDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <Button 
        android:id="@+id/pickDate"
        android:layout_below="@+id/displayDate"
        android:paddingTop="5dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Pick Date" />

</RelativeLayout>



After creating the layout for our application we need to add following code in our MainActivity class.

package com.codingredefined.datepicker;

import java.util.Calendar;

import android.support.v7.app.ActionBarActivity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity
{

private TextView displayDate;
private int mday, mmonth, myear;
static final int DATE_DIALOG_ID = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        displayDate = (TextView)findViewById(R.id.displayDate);
        Button pickDate = (Button)findViewById(R.id.pickDate);
       
        pickDate.setOnClickListener(new View.OnClickListener() {

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

showDialog(DATE_DIALOG_ID);

}
});
   
        final Calendar c = Calendar.getInstance();
        myear = c.get(Calendar.YEAR);
        mmonth = c.get(Calendar.MONTH);
        mday = c.get(Calendar.DAY_OF_MONTH);
        updateDisplay();
       
    }

    @Override
    protected Dialog onCreateDialog(int id)
    {
    switch(id)
    {
    case DATE_DIALOG_ID:
    return new DatePickerDialog(this, dateSetListener, myear, mmonth, mday);
    }
    return null;
    }
   
    protected void onPrepareDialog(int id, Dialog dialog)
    {
    switch(id)
    {
    case DATE_DIALOG_ID:
    ((DatePickerDialog)dialog).updateDate(myear, mmonth, mday);
    break;
    }
    }
   
    private void updateDisplay()
    {
    displayDate.setText(new StringBuilder().append(mmonth +1).append("-").append(mday).append("-").append(myear).append(" "));
    }
   
    private DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {

@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub

myear = year;
mmonth = monthOfYear;
mday = dayOfMonth;
updateDisplay();

}
};
   
    @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;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}







Save the code and run.




Friday, 6 February 2015

Android Broadcast Receiver

Hey, in this tutorial we will learn to implement Broadcast Receiver in your Android app. Broadcast Receivers are implemented to respond to the messages broadcasted by the system or by other applications.

First create a button which will trigger a broadcast from our application.

<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="com.codingredefined.broadcastreceiver.MainActivity" >

    <Button
        android:id="@+id/btnStartService"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Broadcast Intent"
        android:onClick="broadcastIntent"
        />

</RelativeLayout>



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

package com.codingredefined.broadcastreceiver;

import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;


public class MainActivity extends ActionBarActivity {

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


    @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;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    //broadcast a custom intent
    public void broadcastIntent(View view)
    {
    Intent intent= new Intent();
    intent.setAction("com.codingredefined.CUSTOM_INTENT");
    sendBroadcast(intent);
    }
}



Following the changes done in the MainActivity file, then we need to create a new file MyReceiver.java which will respond to the broadcast messages.

package com.codingredefined.broadcastreceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(context, "Broadcast Received", Toast.LENGTH_LONG).show();
}

}


Now finally we need to register our broadcast receiver in the manifest file.

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name="MyReceiver">
            <intent-filter>
                <action android:name="com.codingredefined.CUSTOM_INTENT"></action>
            </intent-filter>
        </receiver>
    </application>

</manifest>



Now the application is ready to run.


Tuesday, 3 February 2015

Android Background Service

Hey, in this tutorial I will demonstrate how to enable your application to continue working in the background without requiring any user interaction.

To start with, first of all create 2 buttons to start and stop the background service.

<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="com.codingreedefined.backgroundservice.MainActivity" >

    <Button
        android:id="@+id/btnStartService"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Start Service"
        android:onClick="startService"
    />
    
    <Button
        android:id="@+id/btnStopService"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btnStartService"
        android:text="Stop Service"
        android:onClick="stopService"
    />

</RelativeLayout>


After creating the buttons write functions to start and stop the background service in MainActivity file.

package com.codingreedefined.backgroundservice;

import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;


public class MainActivity extends ActionBarActivity {

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


    @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;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    //Method to start the service
    public void startService(View view)
    {
    startService(new Intent(getBaseContext(), MyService.class));
    }
    
    //Method to start the service
    public void stopService(View view)
    {
    stopService(new Intent(getBaseContext(), MyService.class));
    }
    
}




Now create a new Java class named MyService and extend Service. Finally write the following code.

package com.codingreedefined.backgroundservice;

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

public class MyService extends Service 
{
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
//let it continue running until it is stopped
Toast.makeText(this, "Service Started!!!", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
@Override
public void onDestroy()
{
super.onDestroy();
Toast.makeText(this, "Service Stopped!!!", Toast.LENGTH_SHORT).show();
}
}


Finally add <service /> tag in the manifest file and run the application.

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".MyService" />
    </application>
</manifest>


The following output shall be obtained.







Sunday, 5 January 2014

Android SQL Lite

Learn to use pre-installed SQL Lite in your Android phone.

Create the following layout to proceed with the example.

<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" >

    <TextView
        android:id="@+id/tv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter Text" />

    <EditText 
        android:id="@+id/et"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"        
        android:layout_below="@+id/tv1"
        android:hint="Enter Here"
        />
    
    <Button 
        android:id="@+id/delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/select"
        android:text="DELETE"
        />

    <Button
        android:id="@+id/update"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/delete"
        android:layout_alignBottom="@+id/delete"
        android:layout_alignLeft="@+id/insert"
        android:text="UPDATE" />

    <Button
        android:id="@+id/select"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:text="SELECT" />

    <Button
        android:id="@+id/insert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/select"
        android:layout_toRightOf="@+id/select"
        android:text="INSERT" />

    <TextView
        android:id="@+id/tv2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/et" />
    
</RelativeLayout>




Now make changes in the activity file.

package com.codingredefined.androidsqlite;

import java.util.Locale;

import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
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
{
EditText et;
TextView tv1,tv2;
Button select,insert,update,delete;
SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et=(EditText)findViewById(R.id.et);
tv1=(TextView)findViewById(R.id.tv1);
tv2=(TextView)findViewById(R.id.tv2);
select=(Button)findViewById(R.id.select);
insert=(Button)findViewById(R.id.insert);
update=(Button)findViewById(R.id.update);
delete=(Button)findViewById(R.id.delete);
//Create DB
db=openOrCreateDatabase("test.db",SQLiteDatabase.CREATE_IF_NECESSARY,null);
db.setVersion(1);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
//Create Table(s)
final String create="CREATE TABLE TEST(daat TEXT);";
db.execSQL(create);
Toast.makeText(this,"Table Created Successfully",Toast.LENGTH_SHORT).show();
select.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
select(v);
}
});
insert.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
insert(v);
}
});
delete.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
delete(v);
}
});
update.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
update(v);
}
});
}

//function to display data
public void up()
{
db=openOrCreateDatabase("test.db",SQLiteDatabase.CREATE_IF_NECESSARY,null);
tv2.setText("");
Cursor cr=db.query("TEST",null,null,null,null,null,null,null);
cr.moveToFirst();
while(cr.isAfterLast()==false)
{
tv2.append("\n"+cr.getString(0));
cr.moveToNext();
}
cr.close();
db.close();
}

public void select(View v)
{
up();
}

//function to insert
public void insert(View v)
{
db=openOrCreateDatabase("test.db",SQLiteDatabase.CREATE_IF_NECESSARY,null);
ContentValues cv=new ContentValues();
cv.put("daat",et.getText().toString());
long a=db.insert("TEST",null,cv);
db.close();
if(a!=0)
{
Toast.makeText(this,"Insert",Toast.LENGTH_SHORT).show();
up();
}
else
{
Toast.makeText(this,"ERROR",Toast.LENGTH_SHORT).show();
}
}

//function to delete
public void delete(View v)
{
db=openOrCreateDatabase("test.db",SQLiteDatabase.CREATE_IF_NECESSARY,null);
db.delete("TEST","daat=?",new String[]{et.getText().toString()});
db.close();
up();
}

//function to update
public void update(View v)
{
db=openOrCreateDatabase("test.db",SQLiteDatabase.CREATE_IF_NECESSARY,null);
ContentValues cv=new ContentValues();
cv.put("daat",et.getText().toString());
db.update("TEST",cv,"daat=?",new String[]{et.getText().toString()});
db.close();
up();
}

@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 output will be




Video Tutorial


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.