Thursday, February 1, 2018

AsyncTask in Android

What is AsyncTask  

               AsyncTask is an abstract class provided by Android which helps us to use the UI thread properly. This class allows us to perform long/background operations and show its result on the UI thread without having to manipulate threads.

  Android implements single thread model and whenever an android application is launched, a thread is created. Assuming we are doing network operation on a button click in our application. On button click a request would be made to the server and response will be awaited. Due to single thread model of android, till the time response is awaited our screen is non-responsive. So we should avoid performing long running operations on the UI thread. This includes file and network access.

Tuesday, February 23, 2016

Activity life cycle

Activity life cycle

Activity is the basic building block of every visible android application. It provides the means to render a GUI. Every screen in an application is an activity by itself. We can call each visible component as an activity in android. Though more than one activities work together to present an application sequence, each activity is an independent entity. Just have a look at the below image, which explains the life cycle of an activity. I will explain the practical use of an activity, when we will develop our first “Hello World” application in this tutorial.

life-cycle-of-an-activity-in-android
Example program :

MainActivity

package com.techblogon.activitylifecycleexample;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Toast.makeText(this, "On Create Called In First Activity", Toast.LENGTH_LONG).show();
        Log.i("FirstActivity", "Inside onCreate");  
    }
    @Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Toast.makeText(this, "On Start Called In First Activity", Toast.LENGTH_LONG).show();
Log.i("FirstActivity", "Inside onStart");
}
    @Override
protected void onResume()
{
// TODO Auto-generated method stub
super.onResume();

Toast.makeText(this, "On Resume Called In First Activity", Toast.LENGTH_LONG).show();
Log.i("FirstActivity", "Inside onResume");
}
 @Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Toast.makeText(this, "On Pause Called In First Activity", Toast.LENGTH_LONG).show();
Log.i("FirstActivity", "Inside onPause");
}
   @Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();

Toast.makeText(this, "On Stop Called In First Activity", Toast.LENGTH_LONG).show();
Log.i("FirstActivity", "Inside onStop");
}
   @Override
protected void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "On Destroy Called In First Activity", Toast.LENGTH_LONG).show();
Log.i("FirstActivity", "Inside onDestroy");

}
public void startSecondActivity(View V)
    {
    // create an new Intent and Start Second Activity
    Intent intent=new Intent(this,SecondActivity.class);
    startActivity(intent);
}
}

Xml coding for mainactivity:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent" 
>
      <TextView
         android:id="@+id/textView1"
         android:layout_gravity="center_horizontal"
         android:textSize="23dp"
         android:layout_marginTop="150dp"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="This Is Fist Activity Activity" 
         />
    
    <Button
        android:id="@+id/button1"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="      Second Activity     " 
        android:onClick="startSecondActivity"/>

</LinearLayout>


Secound Activity:


package com.techblogon.activitylifecycleexample;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class SecondActivity extends Activity
{
    /** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout2);
        Toast.makeText(this, "On Create Called In Second Activity", Toast.LENGTH_LONG).show();
        Log.i("SecondActivity", "Inside onCreate");
         
    }   
    @Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Toast.makeText(this, "On Start Called In Second Activity", Toast.LENGTH_LONG).show();
Log.i("SecondActivity", "Inside onStart");
}  
    @Override
protected void onResume()
{
// TODO Auto-generated method stub
super.onResume();
Toast.makeText(this, "On Resume Called In Second Activity", Toast.LENGTH_LONG).show();
Log.i("SecondActivity", "Inside onResume");
}  
 @Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Toast.makeText(this, "On Pause Called In Second Activity", Toast.LENGTH_LONG).show();
Log.i("SecondActivity", "Inside onPause");
}
   @Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Toast.makeText(this, "On Stop Called In Second Activity", Toast.LENGTH_LONG).show();
Log.i("SecondActivity", "Inside onStop");
}
   @Override
protected void onDestroy() 
{
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "On Destroy Called In Second Activity", Toast.LENGTH_LONG).show();
Log.i("SecondActivity", "Inside onDestroy");
}
}

secoundactivity xml coding:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent" 
>
     <TextView
         android:id="@+id/textView1"
         android:layout_marginTop="150dp"
         android:layout_gravity="center_horizontal"
         android:textSize="23dp"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="This Is Second Activity" />
      </LinearLayout>
     


Output:
android activity lifecycle example

Wednesday, June 17, 2015

Android Drawing Bar Charting

Layout :



<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.bar_graphs.MainActivity" >

    <Button
        android:id="@+id/btn_chart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/str_btn_chart"
        tools:context=".MainActivity" />

</RelativeLayout>


MainActivity :



package com.bar_graphs;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import org.achartengine.ChartFactory;
import org.achartengine.chart.BarChart.Type;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.CategorySeries;
import org.achartengine.model.MultipleCategorySeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;


import android.graphics.Color;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
private String[] mMonth = new String[] {
       "Jan", "Feb" , "Mar", "Apr", "May", "Jun",
       "Jul", "Aug" , "Sep", "Oct", "Nov", "Dec"
   };

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnChart = (Button) findViewById(R.id.btn_chart);
OnClickListener clickListener = new OnClickListener() {
 
           @Override
           public void onClick(View v) {
              
               openChart();
           }
       };
       btnChart.setOnClickListener(clickListener);
}
private void openChart()
{
        int[] x = { 0,1,2,3,4,5,6,7 };
        int[] income = { 2000,2500,2700,3000,2800,3500,3700,3800};
        int[] expense = {2200, 2700, 2900, 2800, 2600, 3000, 3300, 3400 };
        int[] salary = {5000,2000,3000,4000,4000,7010,8520,6000 };
        // Creating an  XYSeries for Income
        XYSeries incomeSeries = new XYSeries("Income");
        // Creating an  XYSeries for Expense
        XYSeries expenseSeries = new XYSeries("Expense");
        // Adding data to Income and Expense Series
        XYSeries salarySeries=new XYSeries("Salary");
        for(int i=0;i<x.length;i++){
            incomeSeries.add(i,income[i]);
            expenseSeries.add(i,expense[i]);
            salarySeries.add(i, salary[i]);
        }
        XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
        dataset.addSeries(incomeSeries);
        dataset.addSeries(expenseSeries);
        dataset.addSeries(salarySeries);
        
        XYSeriesRenderer incomeRenderer = new XYSeriesRenderer();
        incomeRenderer.setColor(Color.rgb(130, 130, 230));
        incomeRenderer.setFillPoints(true);
        incomeRenderer.setLineWidth(2);
        incomeRenderer.setDisplayChartValues(true);
        
        XYSeriesRenderer expenseRenderer = new XYSeriesRenderer();
        expenseRenderer.setColor(Color.rgb(220, 80, 80));
        expenseRenderer.setFillPoints(true);
        expenseRenderer.setLineWidth(2);
        expenseRenderer.setDisplayChartValues(true);
        
        XYSeriesRenderer salaryRenderer = new XYSeriesRenderer();
        incomeRenderer.setColor(Color.rgb(160, 160, 260));
        incomeRenderer.setFillPoints(true);
        incomeRenderer.setLineWidth(2);
        incomeRenderer.setDisplayChartValues(true);
        
        XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer();
        multiRenderer.setXLabels(0);
        multiRenderer.setChartTitle("Income vs Expense and Salary Chart");
        multiRenderer.setXTitle("Year 2012");
        multiRenderer.setYTitle("Amount in Dollars");
        multiRenderer.setZoomButtonsVisible(true);
        for(int i=0; i< x.length;i++){
            multiRenderer.addXTextLabel(i, mMonth[i]);
        }
        
        multiRenderer.addSeriesRenderer(incomeRenderer);
        multiRenderer.addSeriesRenderer(expenseRenderer);
        multiRenderer.addSeriesRenderer(salaryRenderer);
        Intent intent = ChartFactory.getBarChartIntent(getBaseContext(), dataset, multiRenderer, Type.DEFAULT);
        
       
        startActivity(intent);
}
}



OutPut :



Wednesday, May 27, 2015

Login Page

Register class 




package com.example.demo;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;


public class Register extends Activity implements OnClickListener{
protected static final String EXTRA_MESSAGE = null;
private ImageButton ib;
private Calendar cal;
private int day;
private int month;
private int year;
private EditText et;





DatabaseHelpers db;
Spinner gender,state,district,city,qualification;
EditText username,password,conform,name,address,datebirth,mobile,email;

Button register;

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

ib = (ImageButton) findViewById(R.id.imageButton1);
 cal = Calendar.getInstance();
 day = cal.get(Calendar.DAY_OF_MONTH);
 month = cal.get(Calendar.MONTH);
 year = cal.get(Calendar.YEAR);
 et = (EditText) findViewById(R.id.datebirth);
 ib.setOnClickListener(this);


username   =(EditText)findViewById(R.id.username);
password   =(EditText)findViewById(R.id.password);
conform    =(EditText)findViewById( R.id.conformpass);
name       =(EditText)findViewById(R.id.name);
datebirth  =(EditText)findViewById(R.id.datebirth);
address    =(EditText)findViewById(R.id.address1);
mobile     =(EditText)findViewById(R.id.mobile);
email      =(EditText)findViewById(R.id.email);
gender     =(Spinner)findViewById(R.id.gender);
state      =(Spinner)findViewById(R.id.state);
district   =(Spinner)findViewById(R.id.district);
city       =(Spinner)findViewById(R.id.city);
qualification=(Spinner)findViewById(R.id.qualification);

db =new DatabaseHelpers(this);

register=(Button)findViewById(R.id.register);
register.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

String user        =username.getText().toString();
String pass        =password.getText().toString();
String conpass     =conform.getText().toString();
String names       =name.getText().toString();
String datebirths=datebirth.getText().toString();
String addresss=address.getText().toString();
String mob=mobile.getText().toString();
String emails=email.getText().toString();
String genders=gender.getSelectedItem().toString();
String states=state.getSelectedItem().toString();
String districts=district.getSelectedItem().toString();
String citys=city.getSelectedItem().toString();
String quali=qualification.getSelectedItem().toString();

db.add(new Sample(user,pass,names,genders,datebirths,states,districts,citys,addresss,quali,mob,emails));
Toast.makeText(getApplicationContext(), "Your data Created ",Toast.LENGTH_LONG).show();
Intent i=new Intent(Register.this,MainActivity.class);
startActivity(i);
}
});
}

@Override
public void onClick(View v) {
showDialog(0);

}
protected Dialog onCreateDialog(int id) {
 return new DatePickerDialog(this, datePickerListener, year, month, day);

}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
 public void onDateSet(DatePicker view, int selectedYear,
   int selectedMonth, int selectedDay) {
  et.setText(selectedDay + " / " + (selectedMonth + 1) + " / "
    + selectedYear);
 }
};


}





Java Model Class




package com.example.demo;

public class Sample {
private int id;
private String username;
private String password;
private String name;
private String gender,datebirth,state,district,city,address,qualification,mobile,email;
Sample(){
super();
}
public Sample(int id,String username,String password,String name,String 
gender,String datebirth,String state,String district,String city,
String address,String qualification,String mobile,String email)
{
super();
this.id=id;
this.username=username;
this.password=password;
this.name=name;
this.gender=gender;
this.datebirth=datebirth;
this.state=state;
this.district=district;
this.city=city;
this.address=address;
this.qualification=qualification;
this.mobile=mobile;
this.email=email;
}
public Sample(String username,String password,String name ,String 
gender,String datebirth,String state,String district,String city,
String address,String qualification,String mobile,String email)
{
super();
this.username=username;
this.password=password;
this.name=name;
this.gender=gender;
this.datebirth=datebirth;
this.state=state;
this.district=district;
this.city=city;
this.address=address;
this.qualification=qualification;
this.mobile=mobile;
this.email=email;
}

public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getDatebirth() {
return datebirth;
}
public void setDatebirth(String datebirth) {
this.datebirth = datebirth;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getQualification() {
return qualification;
}
public void setQualification(String qualification) {
this.qualification = qualification;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Sample [id=" + id + ", username=" + username + ", password="
+ password + ", name=" + name + ", gender=" + gender
+ ", datebirth=" + datebirth + ", state=" + state + ", district="
+ district + ", city=" + city + ", address=" + address
+ ", qualification=" + qualification + ", mobile=" + mobile
+ ", email=" + email + "]";
}

}



DataBaseHelper Class



package com.example.demo;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelpers extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "counselling.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "register";
private static final String STATE_TABLE="State";
private static final String DISTRICT_TABLE="District";

private static final String KEY_ID = "id";
private static final String KEY_USER_NAME = "Username";
private static final String KEY_PASSWORD = "Password";
private static final String KEY_NAME = "Name";
private static final String KEY_DATABIRTH="DataBirth";
private static final String KEY_GENDER="Gender";
private static final String KEY_STATE="State";
private static final String KEY_DISTRICT="District";
private static final String KEY_CITY="City";
private static final String KEY_ADDRESS="Address";
private static final String KEY_QUALIFICATION="Qualification";
private static final String KEY_MOBILE="Mobile";
private static final String KEY_EMAIL="Email";
public DatabaseHelpers(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}

@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_REGISTER_TABLE;
//String CREATE_STATE_TABLE;
CREATE_REGISTER_TABLE = "create table " + TABLE_NAME + "(" + KEY_ID
+ " integer primary key autoincrement, " + KEY_USER_NAME + " text, " + KEY_PASSWORD
+ " text, " + KEY_NAME + " text, " + KEY_DATABIRTH + " text, " + KEY_GENDER + " text, " + KEY_STATE + " text, " + KEY_DISTRICT +
" text, " + KEY_CITY + " text, " + KEY_ADDRESS + " text, " + KEY_QUALIFICATION + " text, " + KEY_MOBILE + " text, " +
KEY_EMAIL + " text);";
db.execSQL(CREATE_REGISTER_TABLE);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}

void add(Sample l) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues v = new ContentValues();
v.put(KEY_USER_NAME, l.getUsername());
v.put(KEY_PASSWORD, l.getPassword());
v.put(KEY_NAME, l.getName());
v.put(KEY_DATABIRTH, l.getDatebirth());
v.put(KEY_GENDER, l.getGender());
v.put(KEY_STATE, l.getState());
v.put(KEY_DISTRICT, l.getDistrict());
v.put(KEY_CITY, l.getCity());
v.put(KEY_ADDRESS, l.getAddress());
v.put(KEY_QUALIFICATION,l.getQualification());
v.put(KEY_MOBILE, l.getMobile());
v.put(KEY_EMAIL,l.getEmail());
// Inserting Row
db.insert(TABLE_NAME, null, v);
db.close(); // Closing database connection
}

}