Thursday, May 30, 2013

Lambda Expression in Java 8

Current New topic in Java 8 is lambda expressions.Lambda expressions are just like  methods, a body and return type and it has arguments. It is just like anonymous methods or we can say that method without name.

There are fallowing statement about Lembda Expressions:--

1) Lambda expression does't necessory to have parameters.
2) If there are no parameters to be passed, then an empty parentheses is given.
3) Type of the passed parameter can be explicitly declared or can be taken from context.
4) Lambda expression body does't necessory to have statements.
5) Body of expression should be enclosed in curly braces, if there is only one statement curly brace is not needed.
6) Lambda expression is converted into an instance of a functional interface.


There is fallowing example for lemda expression:----

 If we have fallowing list that we want to sort it. We can do it by fallowing way.

List<Person> personList = new ArrayList<>();
personList.add(new Person("Virat", "Kohli"));
personList.add(new Person("Arun", "Kumar"));
personList.add(new Person("Rajesh", "Mohan"));
personList.add(new Person("Rahul", "Dravid"));


//Sorting using Anonymous Inner class.
Collections.sort(personList, new Comparator<Person>(){
public int compare(Person p1, Person p2){
return p1.firstName.compareTo(p2.firstName);
}
});


But We Can reduce the code and more precise by using Lembda Expression as Fallowing:

Collections.sort(personList, (p1, p2) -> p1.firstName.compareTo(p2.firstName));
 



Pyramid Programs in C Languages:


Program 1:-

                              *
                            ***
                          *****
                        *******
                      *********


Solution:

#include <stdio.h>

int main()
{
   int row, c, n, temp;

   printf("Enter the number of rows in pyramid of stars you wish to see ");
   scanf("%d",&n);

   temp = n;

   for ( row = 1 ; row <= n ; row++ )
   {
      for ( c = 1 ; c < temp ; c++ )
         printf(" ");

      temp--;

      for ( c = 1 ; c <= 2*row - 1 ; c++ )
         printf("*");

      printf("\n");
   }

   return 0;
}



Output:-



-------------------------------------------------------------------------------------------------------------



Program 2:-


*
**
***
****
*****


Solution:--

#include <stdio.h>

int main()
{
    int n, c, k;

    printf("Enter number of rows\n");
    scanf("%d",&n);

    for ( c = 1 ; c <= n ; c++ )
    {
        for( k = 1 ; k <= c ; k++ )
            printf("*");

        printf("\n");
    }

    return 0;
}




------------------------------------------------------------------------------------------------------------





 A
B B
C C C
D D D D
E E E E E


Solution :--



#include<stdio.h>
int main()
{
    int i,j;
    char input,temp='A';
    printf("Enter uppercase character you want in triangle at last row: ");
    scanf("%c",&input);
    for(i=1;i<=(input-'A'+1);++i)
    {
        for(j=1;j<=i;++j)
           printf("%c",temp);
        ++temp;
        printf("\n");
    }
    return 0;
}

--------------------------------------------------------------------------------------------------------------



   *
      * * *
    * * * * *
  * * * * * * *
* * * * * * * * *



#include <stdio.h>
int main()
{
    int i,space,rows,k=0;
    printf("Enter the number of rows: ");
    scanf("%d",&rows);
    for(i=1;i<=rows;++i)
    {
        for(space=1;space<=rows-i;++space)
        {
           printf("  ");
        }
        while(k!=2*i-1)
        {
           printf("* ");
           ++k;
        }
        k=0;
        printf("\n");
    }
    return 0;
}




----------------------------------------------------------------------------------------------------------------



      1
      2 3 2
    3 4 5 4 3
  4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5



#include <stdio.h>
int main()
{
   int i,space,rows,k=0,count=0,count1=0;
   printf("Enter the number of rows: ");
   scanf("%d",&rows);
   for(i=1;i<=rows;++i)  
   {
       for(space=1;space<=rows-i;++space)
       {
          printf("  ");
          ++count;
        }
        while(k!=2*i-1)
        {
           if (count<=rows-1)
           {
             printf("%d ",(i+k));
             ++count;
           }
           else
           {
             ++count1;
              printf("%d ", (i+k-2*count1));
           }
           ++k;
        }
        count1=count=k=0;
        printf("\n");
    }
    return 0;
}



================================================================================


* * * * * * * * *
  * * * * * * *
    * * * * *
      * * *
        *
       
       
       
       
       
        #include<stdio.h>
int main()
{
    int rows,i,j,space;
    printf("Enter number of rows: ");
    scanf("%d",&rows);
    for(i=rows;i>=1;--i)
    {
        for(space=0;space<rows-i;++space)
           printf("  ");
        for(j=i;j<=2*i-1;++j)
          printf("* ");
        for(j=0;j<i-1;++j)
            printf("* ");
        printf("\n");
    }
    return 0;
}





=========================================================================



           1
         1   1
       1   2   1
     1   3   3    1
   1  4    6   4   1
 1  5   10   10  5   1

#include<stdio.h>
int main()
{
    int rows,coef=1,space,i,j;
    printf("Enter number of rows: ");
    scanf("%d",&rows);
    for(i=0;i<rows;i++)
    {
        for(space=1;space<=rows-i;space++)
        printf("  ");
        for(j=0;j<=i;j++)
        {
            if (j==0||i==0)
                coef=1;
            else
               coef=coef*(i-j+1)/j;
            printf("%4d",coef);
        }
        printf("\n");
    }
}



===========================================================================


1
2 3
4 5 6
7 8 9 10

#include<stdio.h>
int main()
{
    int rows,i,j,k=0;
    printf("Enter number of rows: ");
    scanf("%d",&rows);
    for(i=1;i<=rows;i++)
    {
        for(j=1;j<=i;++j)
          printf("%d ",k+j);
        ++k;
        printf("\n");
    }
}



Tuesday, May 28, 2013

Side Slider in for Android

Slider on side is more toughest task , i have try to implement it. Below code shows how to implement it.















1:- MainActivity.java:-


package com.example.sideslider;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
CheckBox c1,c2,c3;
int key=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final CustomisedPanel popup = (CustomisedPanel)
findViewById(R.id.popup_window);
popup.setVisibility(View.GONE);
final Button btn=(Button)findViewById(R.id.show_popup_button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if(key==0){
key=1;
popup.setVisibility(View.VISIBLE);
btn.setBackgroundResource(R.drawable.direction_right);
} else if(key==1){
key=0;
popup.setVisibility(View.GONE);
btn.setBackgroundResource(R.drawable.direction_right);
}
}
});
}
}

--------------------------------------------------------------------------------------------------------


2:-CustomisedPanel.java:-


 package com.example.sideslider;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.RectF;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.LinearLayout;
public class CustomisedPanel extends LinearLayout
{
private Paint innerPaint, borderPaint ;
public CustomisedPanel(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomisedPanel(Context context) {
super(context);
init();
}
private void init() {
innerPaint = new Paint();
innerPaint.setARGB(225, 75, 75, 75); //gray
innerPaint.setAntiAlias(true);
borderPaint = new Paint();
borderPaint.setARGB(255, 255, 255, 255);
borderPaint.setAntiAlias(true);
borderPaint.setStyle(Style.STROKE);
borderPaint.setStrokeWidth(2);
}
public void setInnerPaint(Paint innerPaint) {
this.innerPaint = innerPaint;
}
public void setBorderPaint(Paint borderPaint) {
this.borderPaint = borderPaint;
}
@Override
protected void dispatchDraw(Canvas canvas) {
RectF drawRect = new RectF();
drawRect.set(0,0, getMeasuredWidth(), getMeasuredHeight());
canvas.drawRoundRect(drawRect, 5, 5, innerPaint);
canvas.drawRoundRect(drawRect, 5, 5, borderPaint);
super.dispatchDraw(canvas);
}
}
-----------------------------------------------------------------------------------------------



3:-main.xml


 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:gravity="center_vertical"
android:background="@drawable/rectangle"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.example.sideslider.CustomisedPanel
android:id="@+id/popup_window"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:padding="1px"
android:background="#ffffff">
<CheckBox android:id="@+id/check1"
android:layout_width="wrap_content"
android:textColor="#FFFFFF"
android:layout_height="wrap_content"
android:text="Satellite View" />
<CheckBox android:id="@+id/check2"
android:layout_width="wrap_content"
android:textColor="#FFFFFF"
android:layout_height="wrap_content"
android:text="Street View" />
<CheckBox android:id="@+id/check3"
android:textColor="#FFFFFF"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Traffic" />
</com.example.sideslider.CustomisedPanel>
<Button android:id="@+id/show_popup_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/direction_right"/>


</LinearLayout>
------------------------------------------------------------------------------------------------------





Android ListView Indexer



Below I have Declared all code , java classes, xml and Manifiest file also:- 



1:- SideIndex.java file

package andriod.abhi.sideindex;

import java.util.ArrayList;
import java.util.Arrays;

import de.helloandroid.sideindex.R;

import android.app.Activity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

public class SideIndex extends Activity
{
private GestureDetector mGestureDetector;

// x and y coordinates within our side index
private static float sideIndexX;
private static float sideIndexY;

// height of side index
private int sideIndexHeight;

// number of items in the side index
private int indexListSize;

// list with items for side index
private ArrayList<Object[]> indexList = null;

// an array with countries to display in the list
static String[] COUNTRY= new String[]

"British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso",
"Burundi", "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada",
"Cape Verde", "Cayman Islands", "Central African Republic", "Chad",
"Chile", "China", "Reunion", "Romania", "Russia", "Rwanda",
"Sqo Tome and Principe", "Saint Helena", "Saint Kitts and Nevis",
"Saint Lucia", "Saint Pierre and Miquelon", "Belize", "Benin",
"Bermuda", "Bhutan", "Bolivia", "Christmas Island",
"Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
"Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus",
"Czech Republic", "Democratic Republic of the Congo", "Denmark",
"Djibouti", "Dominica", "Dominican Republic",
"Former Yugoslav Republic of Macedonia", "France", "French Guiana",
"French Polynesia", "Macau", "Madagascar", "Malawi", "Malaysia",
"Maldives", "Mali", "Malta", "Marshall Islands", "Yemen",
"Yugoslavia", "Zambia", "Zimbabwe" };

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

// Sortin array
Arrays.sort(COUNTRY);

final ListView lv1 = (ListView) findViewById(R.id.ListView);
lv1.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, COUNTRY));
mGestureDetector = new GestureDetector(this, new SideIndexGestureListener());
}

@Override
public boolean onTouchEvent(MotionEvent event)
{
if (mGestureDetector.onTouchEvent(event))
{
return true;
} else
{
return false;
}
}

private ArrayList<Object[]> createIndex(String[] strArr)
{
ArrayList<Object[]> tmpIndexList = new ArrayList<Object[]>();
Object[] tmpIndexItem = null;

int tmpPos = 0;
String tmpLetter = "";
String currentLetter = null;
String strItem = null;

for (int j = 0; j < strArr.length; j++)
{
strItem = strArr[j];
currentLetter = strItem.substring(0, 1);

// every time new letters comes
// save it to index list
if (!currentLetter.equals(tmpLetter))
{
tmpIndexItem = new Object[3];
tmpIndexItem[0] = tmpLetter;
tmpIndexItem[1] = tmpPos - 1;
tmpIndexItem[2] = j - 1;

tmpLetter = currentLetter;
tmpPos = j + 1;

tmpIndexList.add(tmpIndexItem);
}
}

// save also last letter
tmpIndexItem = new Object[3];
tmpIndexItem[0] = tmpLetter;
tmpIndexItem[1] = tmpPos - 1;
tmpIndexItem[2] = strArr.length - 1;
tmpIndexList.add(tmpIndexItem);

// and remove first temporary empty entry
if (tmpIndexList != null && tmpIndexList.size() > 0)
{
tmpIndexList.remove(0);
}

return tmpIndexList;
}

@Override
public void onWindowFocusChanged(boolean hasFocus)
{
super.onWindowFocusChanged(hasFocus);

final ListView listView = (ListView) findViewById(R.id.ListView);
LinearLayout sideIndex = (LinearLayout) findViewById(R.id.sideIndex);
sideIndexHeight = sideIndex.getHeight();
sideIndex.removeAllViews();


TextView tmpTV = null;

// we'll create the index list
indexList = createIndex(COUNTRY);


indexListSize = indexList.size();

// maximal number of item, which could be displayed
int indexMaxSize = (int) Math.floor(sideIndex.getHeight() / 20);

int tmpIndexListSize = indexListSize;

// handling that case when indexListSize > indexMaxSize
while (tmpIndexListSize > indexMaxSize)
{
tmpIndexListSize = tmpIndexListSize / 2;
}

// computing delta (only a part of items will be displayed to save a
// place)
double delta = indexListSize / tmpIndexListSize;

String tmpLetter = null;
Object[] tmpIndexItem = null;

// show every m-th letter
for (double i = 1; i <= indexListSize; i = i + delta)
{
tmpIndexItem = indexList.get((int) i - 1);
tmpLetter = tmpIndexItem[0].toString();
tmpTV = new TextView(this);
tmpTV.setText(tmpLetter);
tmpTV.setGravity(Gravity.CENTER);
tmpTV.setTextSize(20);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1);
tmpTV.setLayoutParams(params);
sideIndex.addView(tmpTV);
}

// and set a touch listener for it
sideIndex.setOnTouchListener(new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
// now you know coordinates of touch
sideIndexX = event.getX();
sideIndexY = event.getY();

// and can display a proper item it country list
displayListItem();

return false;
}
});
}

class SideIndexGestureListener extends
GestureDetector.SimpleOnGestureListener
{
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY)
{
// we know already coordinates of first touch
// we know as well a scroll distance
sideIndexX = sideIndexX - distanceX;
sideIndexY = sideIndexY - distanceY;

// when the user scrolls within our side index
// we can show for every position in it a proper
// item in the country list
if (sideIndexX >= 0 && sideIndexY >= 0)
{
displayListItem();
}

return super.onScroll(e1, e2, distanceX, distanceY);
}
}

public void displayListItem()
{
// compute number of pixels for every side index item
double pixelPerIndexItem = (double) sideIndexHeight / indexListSize;

// compute the item index for given event position belongs to
int itemPosition = (int) (sideIndexY / pixelPerIndexItem);

// compute minimal position for the item in the list
int minPosition = (int) (itemPosition * pixelPerIndexItem);

// get the item (we can do it since we know item index)
Object[] indexItem = indexList.get(itemPosition);

// and compute the proper item in the country list
int indexMin = Integer.parseInt(indexItem[1].toString());
int indexMax = Integer.parseInt(indexItem[2].toString());
int indexDelta = Math.max(1, indexMax - indexMin);

double pixelPerSubitem = pixelPerIndexItem / indexDelta;
int subitemPosition = (int) (indexMin + (sideIndexY - minPosition) / pixelPerSubitem);

ListView listView = (ListView) findViewById(R.id.ListView);
listView.setSelection(subitemPosition);
}
}

------------------------------------------------------------------------------------------------------------------------------

2:-  main.xml




<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" 
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout 
android:orientation="horizontal"
android:layout_width="fill_parent" 

android:layout_height="wrap_content">
<ListView 
android:id="@+id/ListView" 
android:layout_width="0dp"
android:fastScrollEnabled="true"
android:layout_height="wrap_content" 
android:layout_weight="1">
</ListView>
<LinearLayout 
android:orientation="vertical"
android:background="#FFF" 
android:id="@+id/sideIndex"
android:layout_width="40dip" 
android:layout_height="fill_parent"
android:gravity="center_horizontal">
</LinearLayout>
</LinearLayout>
</LinearLayout>

------------------------------------------------------------------------------------------------------------------------------



3:- Manifiest file:- 



 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="de.helloandroid.sideindex"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name="andriod.abhi.sideindex.SideIndex"
                  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>
    <uses-sdk android:minSdkVersion="3" />

</manifest> 

Customised ListView With Images

Custom ListView with images contains Custom Adapter that i have explained it in below examples:----
1:- CustomListView.java


package com.example.demo;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class CustomListView extends ListActivity {

ArrayList<String> listItems=new ArrayList<String>();

   //DEFINING STRING ADAPTER WHICH WILL HANDLE DATA OF LISTVIEW
//    ArrayAdapter<String> adapter;
MyPerformanceArrayAdapter adapter;
   //RECORDING HOW MUCH TIMES BUTTON WAS CLICKED
   int clickCounter=0;

   @Override
   public void onCreate(Bundle icicle) {
       super.onCreate(icicle);
       setContentView(R.layout.main);
        adapter=new MyPerformanceArrayAdapter(this,listItems);
       setListAdapter(adapter);
   }

   //METHOD WHICH WILL HANDLE DYNAMIC INSERTION
   public void addItems(View v) {
       listItems.add("Clicked : "+clickCounter++);
//    adapter.add(listItems.get(0));
   adapter.notifyDataSetChanged();
   }

   public class MyPerformanceArrayAdapter extends ArrayAdapter<String> {
     private final Activity context;
     private final ArrayList<String> names;

     
     public MyPerformanceArrayAdapter(Activity context, ArrayList<String> listItems) {
       super(context, R.layout.list_layout, listItems);
       this.context = context;
       this.names = listItems;
     }

     @Override
     public View getView(int position, View convertView, ViewGroup parent) {
       View rowView = convertView;
       if (rowView == null) {
         LayoutInflater inflater = context.getLayoutInflater();
         rowView = inflater.inflate(R.layout.list_layout, null);
         ViewHolder viewHolder = new ViewHolder();
         viewHolder.text = (TextView) rowView.findViewById(R.id.textview);
         viewHolder.image = (CheckBox) rowView
             .findViewById(R.id.checkbox);
         rowView.setTag(viewHolder);
       }

       ViewHolder holder = (ViewHolder) rowView.getTag();
       String s = names.get(position);
       holder.text.setText(s);
      
       return rowView;
     }
   
    class ViewHolder {
       public TextView text;
       public CheckBox image;
     }

}
------------------------------------------------------------------------------------------------------------
2:- main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <Button
        android:id="@+id/addBtn"
        android:text="Add New Item"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="addItems"/>
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:drawSelectorOnTop="false"
    />
</LinearLayout>

----------------------------------------------------------------------------------------------------------

3:-  list_layout.xml:- 



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
    
    <CheckBox 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/checkbox"/>
        <TextView 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="hello"
            android:id="@+id/textview"/>
            

</LinearLayout>

Sql Lite Databas in android


Android Fragment Life Cycle



onAttach:_  ( Activity) called once the fragment is associated with its activity.

onCreate():-

System calls this method while creating new fragment. If user want to remain essential componet while other methods call like onPause() or onResume() methods.
    
onCreateView():-
System calls this method when View to be added in activity or draw user interface for user view. it will return View from the method. if we return null, it will not show UI in application.
    









onActivityCreated(Bundle) :- tells the fragment that its activity has completed its own Activity.onCreate().

  onViewStateRestored(Bundle) :_ tells the fragment that all of the saved state of its view hierarchy has been restored.

onStart() :-makes the fragment visible to the user (based on its containing activity being started).

onResume() :- makes the fragment interacting with the user (based on its containing activity being resumed).
As a fragment is no longer being used, it goes through a reverse series of callbacks:


onPause():_It indicate that user leaves this fragment , but it is not going to destroyed. 

onStop() :- fragment is no longer visible to the user either because its activity is being stopped or a fragment operation is modifying it in the activity.

onDestroyView() :- allows the fragment to clean up resources associated with its View.

onDestroy() :- called to do final cleanup of the fragment's state.

onDetach() :- called immediately prior to the fragment no longer being associated with its activity.

    


BroadCast Receiver for Android