Tuesday 30 July 2013

Android Architecture

Leave a Comment
  • Android runs on the top of Linux Operating System.
  • It has Dalvik Virtual Machine (DVM), optimized for mobile phones.
  • It is integrated browser based on Web kit engine.
  • Open GL ES for graphics.
  • Sqlite Support for database.
  • Media Support
  • GSM Technology
  • Bluetooth, EDGE, 3G, wi-fi

Application Fundamentals
  • It is mostly written in java programming language.
  • Final output of the android program is .apk file.
  • Android consist of Components, resources, and AndroidManifest file.
  • Components of Android are:-
  1. Activities
  2. Services
  3. Content Providers
  4. Broadcast Receiver
Activites
  • An Activity represents User Interface which is visible to the user.
  • Typically an android application have many activities.
  • Every Activity in android has a life Cycle.
  • User Interface can be built in XML or Java.
Services
  • Service performs long running operation in the background.
  • Service doesn't have any User Interface.
  • Example:- music player is the example of service.
Content Providers
  • Content Providers is the interface to data for all the application.
  • Can be used to store and retrieve data and make it accessible to all application.
  • Example:- Content Providers for the Contacts, if we want to access phonebook through any application.
Broadcast Receiver
  • It is the component that will respond to the system wide events.
  • It doesn’t have any User Interface.
  • An application can have its own Broadcast Receiver that will respond to the particular event.
  • Example :- Incoming call is an events, that Broadcast Receiver will receive and you can perform some action when any incoming call comes.
Android Manifest file
  • It is in the root of the android project folder.
  • It describes used components in the application.
  • It describes the permission need to run the application.
Read More...

Monday 29 July 2013

How to Send Email in Android Programmatically

Leave a Comment

Today we will learn how to Send Email in android Programmatically. To demonstrate this , I have made a demo project named SendEmail. In this project I have three Textview one for Email Address, one for Subject and last one for message. I am also having one send button,on the tap of it a chooser will popup asking for  Gmail client.
Step 1:-  create main.xml
<LinearLayout 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:orientation="vertical" >

    <EditText
        android:id="@+id/editText_emailAdd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter Email"
        android:inputType="textEmailAddress" >
    </EditText>

    <EditText
        android:id="@+id/editText_subject"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Subject" >
    </EditText>

    <MultiAutoCompleteTextView
        android:id="@+id/multiAutoCompleteTextView_message"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Message" >
    </MultiAutoCompleteTextView>

    <Button
        android:id="@+id/button_send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Send " />

</LinearLayout>

Step 2:- ActivityMain.java
package com.arpit.sendemail;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class ActivityMain extends Activity {
    TextView emailadd, sub, message;
    Button btnsend;

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

        emailadd = (TextView) findViewById(R.id.editText_emailAdd);
        sub = (TextView) findViewById(R.id.editText_subject);
        message = (TextView) findViewById(R.id.multiAutoCompleteTextView_message);
        btnsend = (Button) findViewById(R.id.button_send);

        btnsend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                String emailAddress = emailadd.getText().toString();
                String emailSubject = sub.getText().toString();
                String emailMessage = message.getText().toString();

                // below is the code for sending an email
                Intent emailIntent = new Intent(
                        android.content.Intent.ACTION_SEND);
                emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                        emailAddress);
                emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                        emailSubject);
                emailIntent.setType("plain/text");
                emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
                        emailMessage);
                startActivity(emailIntent);

            }
        });
    }
}

Step 3:- Manifest file
Need to add internet permission in the manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="
http://schemas.android.com/apk/res/android"

    package="com.arpit.sendemail"
    android:versionCode="1"
    android:versionName="1.0" >

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

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

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

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

</manifest>



Catch Me On: CreateAppFaster.com
Read More...

Sunday 28 July 2013

Send sms in Android Programmatically

1 comment
Today we will learn how to send Sms in android Programmatically. It is often required to have the functionality in your application where you want to send some important message or information to other user/receiver. To demonstrate this functionality I have created a simple demo project named Smsdemo. In this project we will be having two text view one for entering number and one for text or message and one send button. On the tap of it, the message will send to number entered number.

Step 1:- create a layout in the project in layout folder, named activity_main.xml
<LinearLayout 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:orientation="vertical" >
    <EditText
        android:id="@+id/EditText_PhoneNumber"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter Number"
        android:inputType="phone" >
    </EditText>
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="250dp" >
        <EditText
            android:id="@+id/MainActivity_Message"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:ems="10"
            android:hint="Enter message"
            android:inputType="textMultiLine" />
    </RelativeLayout>
    <Button
        android:id="@+id/Send_msg_Btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send_Message" />
</LinearLayout>

Step 2:- create a MainActivity.java
package com.example.smsdemo;
import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
    Button send;
    EditText phone_Number, message;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        send = (Button) findViewById(R.id.Send_msg_Btn);   
        phone_Number = (EditText) findViewById(R.id.EditText_PhoneNumber);
        message = (EditText) findViewById(R.id.MainActivity_Message);
        send.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        String phone_Num = phone_Number.getText().toString();
        String send_msg = message.getText().toString();
        try {
            SmsManager sms = SmsManager.getDefault();  // using android SmsManager            sms.sendTextMessage(phone_Num, null, send_msg, null, null);  // adding number and text
        } catch (Exception e) {
            Toast.makeText(this, "Sms not Send", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
}

Step 3:- AndroidManifest
To send the sms in android you need to add one permission mentioned below.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.smsdemo"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.SEND_SMS"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.smsdemo.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>
    </application>
</manifest>
Catch Me On: CreateAppFaster.com
Read More...

List in Android using ListActivity Class

Leave a Comment

List View is one of the group in android, that displays a list of scrollable items. The display of elements in a lists is a very common pattern in mobile applications. The user sees a list of items and can scroll through them. An Adapter is used to list the elements in scrollable manner, which in turn gets the data from the source such as an array or from the database and convert each elements into a view of list.
Some of the commonly used  Adapter are :-
Lets Begin with Coding, to make a list I am using ListActivity Class instead of extending Activity Class.
Step 1:- Set up your project and create the main xml file, my is activity_list.xml
<TextView 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:textSize="25dp"
    android:padding="5dp">
    </TextView>
Step 2:-  In your java file,
package com.arpit.simplelistdemo;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
// I am using ListActivity class instead of Activity
public class ListActivity extends android.app.ListActivity implements OnItemClickListener {
// create the array, this is going to be displayed in a list
  String[] Language = { "JAVA", "JAVASCRIPT", "JQUERY", "JQUERYMOBILE", "C",    
            "ANDRIOD", "PHONEGAP", "DATA STRUCTURE", "WINDOWS", ".NET", "AJAX",
            "C++", "SQL", "HTML5", "CSS3" };
    ListView list;                       
    ArrayAdapter<String> adapter;   // set up an adapter
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
// set up an instance of adapter and passing array and layout to it      
adapter = new ArrayAdapter<String>(this, R.layout.activity_list,
                Language);
        setListAdapter(adapter);
       
        list = getListView();
        list.setOnItemClickListener(this); // click listener on tap of element on list       
    }
    public void onItemClick(AdapterView<?> adapter, View arg1, int position, long arg3) {
       
        String str = adapter.getItemAtPosition(position).toString();
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
       
    }
}
Read More...

Friday 26 July 2013

Check Network Connectivity In Android

Leave a Comment
Today Android Application have lot of dependency on the network to perform functionality. So it is very important to find out if is our device connected to the network before performing any network related task. So, how will you find out if your device connected to the network programmatically.
Lets follow the following steps:-
I have made a separate class to check connection, named CheckConnection.java
This class will help you to find out the network connection of your device. Just create the instance of the class where ever you want to check the network connection, and pass the context of that activity to the CheckConnection.java Class.

// follow the following code

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;

public class CheckConnection {
    NetworkInfo networkInfo, mobileInfo;
    WifiManager wifiSpeedTest;
    Context context;

    public CheckConnection(Context context) {    
        this.context = context;
    }

    public Boolean checkNow() {
        try {
            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            networkInfo = connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            mobileInfo = connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

            if (networkInfo.isConnected() || mobileInfo.isConnected()) {
                return true;
            }
        } catch (Exception e) {
            System.out
                    .println("CheckConnectivity Exception: " + e.getMessage());
        }

        return false;
    }

}
Read More...

Thursday 25 July 2013

Bar Chart in Android using aChartEngine

Leave a Comment
Today we will covered about Bar Chart in android using aChartEngine. To make the bar graph in android, first you have to download the achartengine.jar from code.google.com/p/achartengine/downloads/list. After successfully downloaded the jar file, put that jar file in your libs folder of your android structure. Now take the following step
Step 1:-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.graphdemo"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.graphdemo.GraphActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
<!—Add this activity in your AndroidManifest file -->
        <activity android:name="org.achartengine.GraphicalActivity"/>
    </application>
</manifest>
Step 2:- activity_graph.xml in res folder
<LinearLayout 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:orientation="vertical" >
<Button
      android:id="@+id/BarGraph"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:text="BarGraph" />
</LinearLayout>
Step 3:- GraphActivity.java
package com.arpit.graphdemo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class GraphActivity extends Activity implements OnClickListener {
    Button  barGraph;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_graph);
        barGraph = (Button) findViewById(R.id.BarGraph);
        barGraph.setOnClickListener(this);
       
       
    }
    @Override
    public void onClick(View v) {
       
        switch(v.getId()){
           
              case R.id.BarGraph:
                  BarGraph bar = new BarGraph();
                  Intent barIntent = bar.getIntent(this);
                  startActivity(barIntent);
                  break;
        }
       
    }
}
Step 4: Create a class BarGraph.java
This will be the  class where the graph is actually created by using methods of achartengine library.
package com.arpit.graphdemo;
import org.achartengine.ChartFactory;
import org.achartengine.chart.BarChart.Type;
import org.achartengine.model.CategorySeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
public class BarGraph {
   
    public Intent getIntent(Context context){
       
        int y[] = {25,10,15,20};
       
        CategorySeries series = new CategorySeries("Bar1");
        for(int i=0; i < y.length; i++){
            series.add("Bar"+(i+1),y[i]);
        }
       
        XYMultipleSeriesDataset dataSet = new XYMultipleSeriesDataset();  // collection of series under one object.,there could any
        dataSet.addSeries(series.toXYSeries());                            // number of series
       
        //customization of the chart
   
        XYSeriesRenderer renderer = new XYSeriesRenderer();     // one renderer for one series
        renderer.setColor(Color.RED);
        renderer.setDisplayChartValues(true);
        renderer.setChartValuesSpacing((float) 5.5d);
        renderer.setLineWidth((float) 10.5d);
           
       
        XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();   // collection multiple values for one renderer or series
        mRenderer.addSeriesRenderer(renderer);
        mRenderer.setChartTitle("Demo Graph");
//        mRenderer.setXTitle("xValues");
        mRenderer.setYTitle("Rupee");
        mRenderer.setZoomButtonsVisible(true);    mRenderer.setShowLegend(true);
        mRenderer.setShowGridX(true);      // this will show the grid in  graph
        mRenderer.setShowGridY(true);             
//        mRenderer.setAntialiasing(true);
        mRenderer.setBarSpacing(.5);   // adding spacing between the line or stacks
        mRenderer.setApplyBackgroundColor(true);
        mRenderer.setBackgroundColor(Color.BLACK);
        mRenderer.setXAxisMin(0);
//        mRenderer.setYAxisMin(.5);
        mRenderer.setXAxisMax(5);
        mRenderer.setYAxisMax(50);
//   
        mRenderer.setXLabels(0);
        mRenderer.addXTextLabel(1,"Income");
        mRenderer.addXTextLabel(2,"Saving");
        mRenderer.addXTextLabel(3,"Expenditure");
        mRenderer.addXTextLabel(4,"NetIncome");
        mRenderer.setPanEnabled(true, true);    // will fix the chart position
     Intent intent = ChartFactory.getBarChartIntent(context, dataSet, mRenderer,Type.DEFAULT);
       
                return intent;
    }
}



bar

Read More...

Image Toast in Android

Leave a Comment
In android we have seen the simple Toast message, that will display simple text. But Today I told you how to display an image along with the toast message.
In this application, on the Button click a simple toast will pop out along with image.
Lets begins with the sample for Image Toast in Android.

Step 1:- activity_main.xml
<LinearLayout 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"
>
<Button
    android:id="@+id/btn_click"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
   android:text="clickme"/>
</LinearLayout>

Step 2:- MainActivity.java
package com.arpit.androidimagetoast;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
    Button btnclick;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnclick = (Button) findViewById(R.id.btn_click);
        btnclick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast imageToast = new Toast(MainActivity.this);
                 // set the layout
                LinearLayout layout = new LinearLayout(getBaseContext());
                layout.setOrientation(LinearLayout.HORIZONTAL);
               // set the text that will be display
                TextView txt = new TextView(getBaseContext());
                txt.setText("hello");
                // set the image from the drawable
                ImageView img = new ImageView(getBaseContext());
                img.setImageResource(R.drawable.user);
                // addview to the layout
                layout.addView(img);
                layout.addView(txt);
                imageToast.setView(layout);
                imageToast.setDuration(Toast.LENGTH_LONG);
                imageToast.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;
    }
}


Screenshot_2013-07-25-19-15-03
Read More...

Block Incoming Calls Android

Leave a Comment

Today I will Explain how to block all incoming calls in android. To block the incoming calls I have to use Broadcast Receiver.
Broadcast Receiver is one of the main android component which allow your application to register for the Events i.e system or application events(Both). Registered Event will be notified by the android run time once the event occurs.

Step 1: create BlockCallReceiver.java
package com.arpit.blockincomingcall;
import java.lang.reflect.Method;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;

public class BlockCallReceiver extends BroadcastReceiver{
   
     Context context;
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
         Bundle myBundle = intent.getExtras();
         if (myBundle != null)
          {
             System.out.println("--------Not null-----");
             try
             {
              if (intent.getAction().equals("android.intent.action.PHONE_STATE"))
              {
                  String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
                  System.out.println("--------in state-----");
                  if (state.equals(TelephonyManager.EXTRA_STATE_RINGING))
                  {
                      // Incoming call
                    String incomingNumber =intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
                    System.out.println("--------------my number---------"+incomingNumber);
                                  
// this is main section of the code,. could also be use for particular number.
                    // Get the boring old TelephonyManager.

                          TelephonyManager telephonyManager =(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                      
                          // Get the getITelephony() method                          Class<?> classTelephony = Class.forName(telephonyManager.getClass().getName());
                          Method methodGetITelephony = classTelephony.getDeclaredMethod("getITelephony");
                   
                          // Ignore that the method is supposed to be private                          methodGetITelephony.setAccessible(true);
                   
                          // Invoke getITelephony() to get the ITelephony interface
                          Object telephonyInterface = methodGetITelephony.invoke(telephonyManager);
                   
                          // Get the endCall method from ITelephony
                          Class<?> telephonyInterfaceClass = Class.forName(telephonyInterface.getClass().getName());
                          Method methodEndCall = telephonyInterfaceClass.getDeclaredMethod("endCall");
                   
                          // Invoke endCall()
                          methodEndCall.invoke(telephonyInterface);
                    
                  }
                   
                }
               }
              catch (Exception ex)
              { // Many things can go wrong with reflection calls
                  ex.printStackTrace();
              }
             }
    }
}
Step 2: Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.arpit.blockincomingcall"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
<!-- permission to be used to block the incoming calls -->
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
    <uses-permission android:name="android.permission.CALL_PHONE" />

    <uses-feature
        android:name="android.hardware.telephony"
        android:required="false" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

     <!—receiver -->
   <receiver android:name=".BlockCallReceiver" >
            <intent-filter android:priority="100" >
                <action android:name="android.intent.action.PHONE_STATE" >
                </action>
            </intent-filter>
        </receiver>

        <activity
            android:name="com.arpit.blockincomingcall.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>
    </application>
</manifest>



Catch Me On: CreateAppFaster.com
Read More...

Pie Charts in Android Using achartEngine

Leave a Comment
We often Required to present  data in Pictorial View(chart)  in our android application. Today I will implement the pie chart using achartengine library for android application.  I have downloaded the library  achartengine.jar from http://www.achartengine.org/
Create an android Project in your Eclipse IDE, I have created one with named GraphChart.

Step 1:- Add chart activity in manifest
GraphChartManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.graphchart"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
         >
        <activity
            android:name="com.arpit.graphchart.Graph"
            android:label="@string/app_name"
          >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
  </activity>
<!—Add this activity in your AndroidManifest file -->
  <activity android:name="org.achartengine.GraphicalActivity"/>    
  </application>
</manifest>
Step 2:- Creating a xml file
activity_graph.xml
we don’t need any xml for displaying. I am using xml for having a button on it, which in turn open my graphical activity.
<LinearLayout 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:orientation="vertical"
    >
    <Button
        android:id="@+id/Efforts_bt_Graph"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Efforts" />
</LinearLayout>
Step 3:-Create Java file 
Graph.java
package com.arpit.graphchart;
import com.graphchart.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Graph extends Activity implements OnClickListener {
    Button efforts;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_graph);
        efforts = (Button) findViewById(R.id.Efforts_bt_Graph);
        efforts.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch(v.getId()){
        case R.id.Efforts_bt_Graph:
            EffortChart effort = new EffortChart();
            Intent effortIntent = effort.getIntent(this);
            startActivity(effortIntent);
            break;
        }
    }
    }
Step 4:- Java file for Creating actual chart
EffortChart.java
package com.arpit.graphchart;
import org.achartengine.ChartFactory;
import org.achartengine.model.CategorySeries;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
public class EffortChart {
    public Intent getIntent(Context context){
      // this is my data of performance; data is collected in array.
       int []Performance = {42, 15, 19};  // [0] for Call, [1] for Meeting, [2] for Email
        CategorySeries series = new CategorySeries("pie"); // adding series to charts. //collect 3 value in array. therefore add three series.
            series.add("Call",Performance[0]);           
            series.add("Meeting",Performance[1]);
            series.add("Email",Performance[2]);
// add three colors for three series respectively            int []colors = new int[]{Color.MAGENTA, Color.WHITE, Color.GREEN};
// set style for series
            DefaultRenderer renderer = new DefaultRenderer();
            for(int color : colors){
                SimpleSeriesRenderer r = new SimpleSeriesRenderer();
                r.setColor(color);
                r.setDisplayBoundingPoints(true);
                r.setDisplayChartValuesDistance(5);
                r.setDisplayChartValues(true);
                r.setChartValuesTextSize(15);
                renderer.addSeriesRenderer(r);
            }
            renderer.isInScroll();
            renderer.setZoomButtonsVisible(true);   //set zoom button in Graph
            renderer.setApplyBackgroundColor(true);
            renderer.setBackgroundColor(Color.BLACK); //set background color
            renderer.setChartTitle("Efforts");
            renderer.setChartTitleTextSize((float) 30);
            renderer.setShowLabels(true); 
            renderer.setLabelsTextSize(20);
            renderer.setLegendTextSize(25);
            renderer.setDisplayValues(true);
            return ChartFactory.getPieChartIntent(context, series, renderer, "PieChart");
        }
    }
piechart

Catch Me On: CreateAppFaster.com

Read More...

Wednesday 24 July 2013

Reading Contacts in a List Android

Leave a Comment
In Android Application it is often required to read the contacts from the Phone Contact Book and perform some operation. Today we study how to read Contacts from your phone and display them in a list. To do the same, set up a project in Eclipse IDE.
Set up the Main Xml where the List populate:-
main.xml:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:cacheColorHint="#00000000" >
    </ListView>
</LinearLayout>
Now set up an another xml, how each row looks like
alluser_row.xml :-
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relativelay"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/tvname"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="3dp"
        android:layout_marginTop="3dp"
        android:ellipsize="end"
        android:maxLines="1"
        android:text="Title"
        android:textColor="#000000"
        android:textSize="17dp"
        android:textStyle="bold" >
    </TextView>
    <TextView
        android:id="@+id/tvphone"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tvname"
        android:layout_marginLeft="3dp"
        android:layout_marginTop="10dp"
        android:ellipsize="end"
        android:maxLines="1"
        android:text="Phone no"
        android:textColor="#000000"
        android:textSize="14dp" >
    </TextView>
</RelativeLayout>
Now switch to javacode
MainActivity.java:-
package com.arpit.listcontactreaderandroid;
import java.util.ArrayList;
import java.util.List;
import com.example.customlistcontactreader.R;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity implements {
    private ListView listView;
    private List<ContactModel> list = new ArrayList<ContactModel>();
    int count=0;                                 // count the number of contacts
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
   
   
        listView = (ListView) findViewById(R.id.list);
       
        Cursor phones = getContentResolver().query(              
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
                null, null);
        while (phones.moveToNext()) {
            count++;
           
            String name = phones
                    .getString(phones
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String phoneNumber = phones
                    .getString(phones
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            ContactModel objContact = new ContactModel();       // creating an instance for contactmodel
            objContact.setName(name);
            objContact.setPhoneNo(phoneNumber);
            list.add(objContact);                                               // adding contacts into the list
        }
        phones.close();
        System.out.println(count);                                               // total numbers of contacts
   
        listView.setAdapter(new ContactCustomAdapter(list, this));   // setting listview with an adapter
       
       
    }
          
    }
}
ContactModel.java:-
// model
package com.arpit.listcontactreaderandroid;
public class ContactModel {
    private String name;
    private String phoneNo;

   
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPhoneNo() {
        return phoneNo;
    }
    public void setPhoneNo(String phoneNo) {
        this.phoneNo = phoneNo;
    }
   
    }
// setting up an adapter for the list
ContactCustomAdapter.java
package com.arpit.listcontactreaderandroid;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
public class ContactCustomAdapter extends BaseAdapter {
    private List<ContactBean> list;
    Context context;
   
    ContactCustomAdapter (List<ContactBean> list, Context context){
        this.list = list;
        this.context = context;
    }
   
   
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }
    @Override
    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return list.get(arg0);
    }
    @Override
    public long getItemId(int arg0) {
        // TODO Auto-generated method stub
        return arg0;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View v = convertView;
        if (v == null)
        {
           LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
           v = vi.inflate(R.layout.alluser_row, null);
        }
          TextView contactName = (TextView)v.findViewById(R.id.tvname);
          TextView contactPhone = (TextView)v.findViewById(R.id.tvphone);
        
         
         ContactModel msg = list.get(position);
          contactName.setText(msg.getName());
          contactPhone.setText(msg.getPhoneNo());                  
                      
       return v;
    }

}
Read More...

Friday 19 July 2013

Android Splash Screen

Leave a Comment
Today we will covered how to make Android Splash Screen.
Splash is the first screen in the Standard Mobile Application which holds itself for 5-10 seconds before moving to the main screen.
Splash screen is useful where we could initialize application level variable or run any background process.Apart from that, we Could have image of company making that application or application name itself.
 
 After Setting up the project, this is required code that will help you make Splash screen.
 
public class Splash extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_splash);    // mapping of xml (Splash) into java

// setting up a thread
  Thread splashThread = new Thread() {
@Override
public void run() {
try {
int waited = 0;
while (waited < 3000) {       // this screen hold itself for 3sec
sleep(100);
waited += 100;
}
} catch (InterruptedException e) {
// do nothing
} finally {
finish();
Intent i = new Intent();
i.setClass(getBaseContext(), RegisterActivity.class);  // RegisterActivity is the                                                                                                  //activity which opens after the splash screen
startActivity(i);
}
}
};
splashThread.start();   // starting of thread
}

}

In xml :---
<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:background="@drawable/splash" >
                                                           <!-- this the image/pic which will come in splash screen
                                                                               saved in drawable folder -->

</RelativeLayout>
 
Result:-
 


Technorati Tags:
Read More...