Monday, 16 December 2013

Using db4o in Android

db4o is a Object oriented database. This tutorial was written to get you started with db4o as quickly as possible. Before you start, please make sure that you have downloaded the latest db4o distribution from the db4objects website.
In this tutorial I have used db4o-8.0.184.15484-all-java5.jar from java2s.com

Then kindly put the file in your project's lib folder and configure project's Build Path.

Enough, Let us start !!!

1. Create a class to configure db4o. I named it as Db4oHelper.

Code:

Db4oHelper.java


import java.io.IOException;

import android.content.Context;
import android.util.Log;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.config.EmbeddedConfiguration;

public class Db4oHelper {

 private static ObjectContainer oc = null;
 private Context context;

 /**
  * @param ctx
  */
 public Db4oHelper(Context ctx) {
  context = ctx;
 }

 /**
  * Create, open and close the database
  */
 public ObjectContainer db() {

  try {
   if (oc == null || oc.ext().isClosed()) {
    oc = Db4oEmbedded.openFile(dbConfig(), db4oDBFullPath(context));
   }

   return oc;

  } catch (Exception ie) {
   Log.e(Db4oHelper.class.getName(), ie.toString());
   return null;
  }
 }

 /**
  * Configure the behavior of the database
  */

 private EmbeddedConfiguration dbConfig() throws IOException {
  EmbeddedConfiguration configuration = Db4oEmbedded.newConfiguration();
  configuration.common().objectClass(Student.class).objectField("name")
    .indexed(true);
  configuration.common().objectClass(Student.class).cascadeOnUpdate(true);
  configuration.common().objectClass(Student.class)
    .cascadeOnActivate(true);
  return configuration;
 }

 /**
  * Returns the path for the database location
  */

 private String db4oDBFullPath(Context ctx) {
  return ctx.getDir("data", 0) + "/" + "myDatabase.db4o";
 }

 /**
  * Closes the database
  */

 public void close() {
  if (oc != null)
   oc.close();
 }
}


2. Create a class to access db4o. I named it as DB4OProvider.

Code:

DB4OProvider.java


import java.util.List;

import android.content.Context;

public class DB4OProvider extends Db4oHelper {

 private static DB4OProvider provider = null;

 //configure Db4oHelper by Passing Context.
 public DB4OProvider(Context ctx) {
  super(ctx);
 }

 public static DB4OProvider getInstance(Context ctx) {
  if (provider == null)
   provider = new DB4OProvider(ctx);
  return provider;
 }

 //This method is used to store the object into the database.
 public void store(Student exercise) {
  db().store(exercise);
 }

 //This method is used to delete the object into the database.
 public void delete(Student exercise) {
  db().delete(exercise);
 }

 //This method is used to retrive all object from database.
 public List<Student> findAll() {  
  return db().query(Student.class);
 }

 //This method is used to retrive matched object from database.
 public List<Student> getRecord(Student s) {  
  return db().queryByExample(s);
 }
// public ObjectSet<Student> getAllData() {
//  Student proto = new Student(null, null, 0);
//  ObjectSet result = db().queryByExample(proto);
//  return result;
// }

}


3. Create a Object class. I named it as Student.

Code:

Student.java

public class Student {

 String name;
 String number;
 int age;

 //constructor, to initialize all variables
 public Student(String name, String number, int age) {
  this.name = name;
  this.age = age;
  this.number = number;
 }

 //Object will return in this format.
 public String toString() {
  return name + "/" + number + "/" + Integer.toString(age);
 }
}


4. Create Activity class to work on. In my case it is MainActivity.java

Code:

MainActivity.java

package com.db4o.db4oexample;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MainActivity extends Activity {

 DB4OProvider ep;
 EditText et_Name, et_Age, et_Number;
 Student c;
 String name = "", number = "";
 int age = 0;
 ArrayList<HashMap<String, Object>> mylist;
 ListView mListView;

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

  et_Name = (EditText) findViewById(R.id.editText1);
  et_Age = (EditText) findViewById(R.id.editText2);
  et_Number = (EditText) findViewById(R.id.editText3);

  ep = new DB4OProvider(this);
 }

 public void onSubmit(View v) {
  name = et_Name.getText().toString();
  age = Integer.parseInt(et_Age.getText().toString());
  number = et_Number.getText().toString();

  c = new Student(name, number, age);
  ep.store(c); // store the database into the database.

  Student s1 = new Student(null, null, 12);// to retrieve object which has
             // age value as 12.
  System.out.println("Get Record : " + ep.getRecord(s1));
  listResult(ep.findAll());// to retrieve all objects.
 }

 // This method is used to display all objects as ListView.
 public void listResult(List<Student> result) {
  mylist = new ArrayList<HashMap<String, Object>>();
  for (Student s : result) {
   HashMap<String, Object> map = new HashMap<String, Object>();
   map.put("name", s.name);
   map.put("age", s.age);
   map.put("number", s.number);
   mylist.add(map);
  }

  ListAdapter adapter = new SimpleAdapter(this, mylist,
    R.layout.list_data, new String[] { "name", "age", "number" },
    new int[] { R.id.tv_name, R.id.tv_age, R.id.tv_num });
  mListView = (ListView) findViewById(R.id.listView1);
  mListView.setAdapter(adapter);
 }

}


And your activity_main.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: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/editText1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:ems="10"
        android:hint="@string/name" >
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:ems="10"
        android:inputType="number"
        android:hint="@string/age" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText2"
        android:ems="10"
        android:inputType="number"
        android:hint="@string/reg_no" />

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText3"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/button1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="onSubmit"
            android:text="@string/submit" />

        <Button
            android:id="@+id/button2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="onClear"
            android:text="@string/clear" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/linearLayout1"
        android:layout_below="@+id/linearLayout1"
        android:layout_marginTop="5dp"
        android:background="@drawable/listview_shape"
        android:orientation="vertical" >

        <TextView
            android:background="@drawable/shape_head"
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:gravity="center"
            android:textColor="#fff"
            android:textSize="18sp"
            android:text="Records as List" />

        <ListView
            android:id="@+id/listView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
        </ListView>
    </LinearLayout>

</RelativeLayout>


And your list_data.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:baselineAligned="false"
    android:gravity="center"
    android:orientation="horizontal"
    android:padding="10dp" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/tv_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/tv_age"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="right" >

        <TextView
            android:id="@+id/tv_num"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

</LinearLayout>


And here is the shape_head.xml


<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <gradient
        android:angle="90"
        android:endColor="#0066CC"
        android:startColor="#003D7A" />

    <corners
        android:bottomLeftRadius="0dp"
        android:bottomRightRadius="0dp"
        android:radius="0.1dp"
        android:topLeftRadius="7dp"
        android:topRightRadius="7dp" />

</shape>


And here is the listview_shape.xml


<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <corners
        android:bottomLeftRadius="7dp"
        android:bottomRightRadius="7dp"
        android:radius="0.1dp"
        android:topLeftRadius="7dp"
        android:topRightRadius="7dp" />

    <solid android:color="#FFFFFF" />

    <stroke
        android:width="1dp"
        android:color="#cccccc" />
</shape>


Sample Screen Shot


I hope this post is useful. kindly share your feedback as comment here.


Thank You



Monday, 18 November 2013

Simple drawing example in Android

This post is a simple drawing example using Canvas, BitMap, Paint and Path classes from Android.
Code:

MainActivity.java

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;

public class DrwaingActivity extends Activity {

 View mView; 
 private Paint mPaint;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  LinearLayout layout = (LinearLayout) findViewById(R.id.myDrawing);
  mView = new DrawingView(this);
  layout.addView(mView, new LayoutParams(
    LinearLayout.LayoutParams.MATCH_PARENT,
    LinearLayout.LayoutParams.MATCH_PARENT));
  init(); 
 }

 private void init() {
  mPaint = new Paint();
  mPaint.setDither(true);
  mPaint.setColor(0xFFFFFF00);
  mPaint.setStyle(Paint.Style.STROKE);
  mPaint.setStrokeJoin(Paint.Join.ROUND);
  mPaint.setStrokeCap(Paint.Cap.ROUND);
  mPaint.setStrokeWidth(3);
 }

 class DrawingView extends View {
  private Path path;
  private Bitmap mBitmap;
  private Canvas mCanvas;

  public DrawingView(Context context) {
   super(context);
   path = new Path();
   mBitmap = Bitmap.createBitmap(820, 480, Bitmap.Config.ARGB_8888);
   mCanvas = new Canvas(mBitmap);
   this.setBackgroundColor(Color.BLACK);
  }

  private ArrayList<PathWithPaint> _graphics1 = new ArrayList<PathWithPaint>();

  @Override
  public boolean onTouchEvent(MotionEvent event) {
   PathWithPaint pp = new PathWithPaint();
   mCanvas.drawPath(path, mPaint);
   if (event.getAction() == MotionEvent.ACTION_DOWN) {
    path.moveTo(event.getX(), event.getY());
    path.lineTo(event.getX(), event.getY());
   } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
    path.lineTo(event.getX(), event.getY());
    pp.setPath(path);
    pp.setmPaint(mPaint);
    _graphics1.add(pp);
   }
   invalidate();
   return true;
  }

  @Override
  protected void onDraw(Canvas canvas) {
   super.onDraw(canvas);
   if (_graphics1.size() > 0) {
    canvas.drawPath(
      _graphics1.get(_graphics1.size() - 1).getPath(),
      _graphics1.get(_graphics1.size() - 1).getmPaint());
   }
  }
 }
}


MainLayout.java

import android.graphics.Paint;
import android.graphics.Path;

public class PathWithPaint {
 private Path path;

 public Path getPath() {
  return path;
 }

 public void setPath(Path path) {
  this.path = path;
 }

 private Paint mPaint;

 public Paint getmPaint() {
  return mPaint;
 }

 public void setmPaint(Paint mPaint) {
  this.mPaint = mPaint;
 }
}


activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/myDrawing"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

</LinearLayout>


Sample Screen Shot


Drawing example with Color Picker



I hope this post is useful. kindly share your feedback as comment here.


Thank You



Monday, 4 November 2013

Simple Sliding Menu Example in Android

Consider using simple NavigationView instead of this old sliding menu , which based on Material design and much simpler and very flexible than this Navigation drawer.

This post will help you to create a simple sliding menu in Android.
Here sliding menu is a listview which is in INVISIBLE state. It will comes to VISIBLE state once you click the menu button. And it will go to INVISIBLE state again once you pick the item from listview. To change the state we are using animation, that is why it looks like sliding.

Complete code:

MainActivity.java

package com.android.slidingmenuexample;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

public class MainActivity extends FragmentActivity {

 MainLayout mLayout;
 private ListView lvMenu;
 private String[] lvMenuItems;
 Button btMenu;
 TextView tvTitle;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  mLayout = (MainLayout) this.getLayoutInflater().inflate(
    R.layout.activity_main, null);
  setContentView(mLayout);

  lvMenuItems = getResources().getStringArray(R.array.menu_items);
  lvMenu = (ListView) findViewById(R.id.menu_listview);
  lvMenu.setAdapter(new ArrayAdapter<String>(this,
    android.R.layout.simple_list_item_1, lvMenuItems));
  lvMenu.setOnItemClickListener(new OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> parent, View view,
     int position, long id) {
    onMenuItemClick(parent, view, position, id);
   }

  });

  btMenu = (Button) findViewById(R.id.button_menu);
  btMenu.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    // Show/hide the menu
    toggleMenu(v);
   }
  });

  tvTitle = (TextView) findViewById(R.id.activity_main_content_title);

  FragmentManager fm = MainActivity.this.getSupportFragmentManager();
  FragmentTransaction ft = fm.beginTransaction();
  Layout1 fragment = new Layout1();
  ft.add(R.id.activity_main_content_fragment, fragment);
  ft.commit();

 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

 public void toggleMenu(View v) {
  mLayout.toggleMenu();
 }

 private void onMenuItemClick(AdapterView<?> parent, View view,
   int position, long id) {
  String selectedItem = lvMenuItems[position];
  String currentItem = tvTitle.getText().toString();
  if (selectedItem.compareTo(currentItem) == 0) {
   mLayout.toggleMenu();
   return;
  }

  FragmentManager fm = MainActivity.this.getSupportFragmentManager();
  FragmentTransaction ft = fm.beginTransaction();
  Fragment fragment = null;

  if (selectedItem.compareTo("Layout 1") == 0) {
   fragment = new Layout1();
  } else if (selectedItem.compareTo("Layout 2") == 0) {
   fragment = new Layout2();
  }

  if (fragment != null) {
   ft.replace(R.id.activity_main_content_fragment, fragment);
   ft.commit();
   tvTitle.setText(selectedItem);
  }
  mLayout.toggleMenu();
 }

 @Override
 public void onBackPressed() {
  if (mLayout.isMenuShown()) {
   mLayout.toggleMenu();
  } else {
   super.onBackPressed();
  }
 }
}


MainLayout.java

package com.android.slidingmenuexample;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Interpolator;
import android.widget.LinearLayout;
import android.widget.Scroller;

public class MainLayout extends LinearLayout {

 private static final int SLIDING_DURATION = 500;
 private static final int QUERY_INTERVAL = 16;
 int mainLayoutWidth;
 private View menu;
 private View content;
 private static int menuRightMargin = 15;

 private enum MenuState {
  HIDING, HIDDEN, SHOWING, SHOWN,
 };

 private int contentXOffset;
 private MenuState currentMenuState = MenuState.HIDDEN;
 private Scroller menuScroller = new Scroller(this.getContext(),
   new EaseInInterpolator());
 private Runnable menuRunnable = new MenuRunnable();
 private Handler menuHandler = new Handler();
 int prevX = 0;
 boolean isDragging = false;
 int lastDiffX = 0;

 public MainLayout(Context context, AttributeSet attrs) {
  super(context, attrs);
 }

 public MainLayout(Context context) {
  super(context);
 }

 @Override
 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  super.onMeasure(widthMeasureSpec, heightMeasureSpec);

  mainLayoutWidth = MeasureSpec.getSize(widthMeasureSpec);
  menuRightMargin = mainLayoutWidth * 10 / 100;
 }

 @Override
 protected void onAttachedToWindow() {
  super.onAttachedToWindow();

  menu = this.getChildAt(0);
  content = this.getChildAt(1);
  content.setOnTouchListener(new OnTouchListener() {
   @Override
   public boolean onTouch(View v, MotionEvent event) {
    return MainLayout.this.onContentTouch(v, event);
   }
  });
  menu.setVisibility(View.GONE);
 }

 @Override
 protected void onLayout(boolean changed, int left, int top, int right,
   int bottom) {
  if (changed) {
   LayoutParams contentLayoutParams = (LayoutParams) content
     .getLayoutParams();
   contentLayoutParams.height = this.getHeight();
   contentLayoutParams.width = this.getWidth();
   LayoutParams menuLayoutParams = (LayoutParams) menu
     .getLayoutParams();
   menuLayoutParams.height = this.getHeight();
   menuLayoutParams.width = this.getWidth() - menuRightMargin;
  }
  menu.layout(left, top, right - menuRightMargin, bottom);
  content.layout(left + contentXOffset, top, right + contentXOffset,
    bottom);

 }

 public void toggleMenu() {

  if (currentMenuState == MenuState.HIDING
    || currentMenuState == MenuState.SHOWING)
   return;

  switch (currentMenuState) {
  case HIDDEN:
   currentMenuState = MenuState.SHOWING;
   menu.setVisibility(View.VISIBLE);
   menuScroller.startScroll(0, 0, menu.getLayoutParams().width, 0,
     SLIDING_DURATION);
   break;
  case SHOWN:
   currentMenuState = MenuState.HIDING;
   menuScroller.startScroll(contentXOffset, 0, -contentXOffset, 0,
     SLIDING_DURATION);
   break;
  default:
   break;
  }
  menuHandler.postDelayed(menuRunnable, QUERY_INTERVAL);
  this.invalidate();
 }

 protected class MenuRunnable implements Runnable {
  @Override
  public void run() {
   boolean isScrolling = menuScroller.computeScrollOffset();
   adjustContentPosition(isScrolling);
  }
 }

 private void adjustContentPosition(boolean isScrolling) {
  int scrollerXOffset = menuScroller.getCurrX();

  content.offsetLeftAndRight(scrollerXOffset - contentXOffset);

  contentXOffset = scrollerXOffset;
  this.invalidate();
  if (isScrolling)
   menuHandler.postDelayed(menuRunnable, QUERY_INTERVAL);
  else
   this.onMenuSlidingComplete();
 }

 private void onMenuSlidingComplete() {
  switch (currentMenuState) {
  case SHOWING:
   currentMenuState = MenuState.SHOWN;
   break;
  case HIDING:
   currentMenuState = MenuState.HIDDEN;
   menu.setVisibility(View.GONE);
   break;
  default:
   return;
  }
 }

 protected class EaseInInterpolator implements Interpolator {
  @Override
  public float getInterpolation(float t) {
   return (float) Math.pow(t - 1, 5) + 1;
  }

 }

 public boolean isMenuShown() {
  return currentMenuState == MenuState.SHOWN;
 }

 public boolean onContentTouch(View v, MotionEvent event) {
  if (currentMenuState == MenuState.HIDING
    || currentMenuState == MenuState.SHOWING)
   return false;
  int curX = (int) event.getRawX();
  int diffX = 0;

  switch (event.getAction()) {
  case MotionEvent.ACTION_DOWN:

   prevX = curX;
   return true;

  case MotionEvent.ACTION_MOVE:
   if (!isDragging) {
    isDragging = true;
    menu.setVisibility(View.VISIBLE);
   }
   diffX = curX - prevX;
   if (contentXOffset + diffX <= 0) {
    diffX = -contentXOffset;
   } else if (contentXOffset + diffX > mainLayoutWidth
     - menuRightMargin) {
    diffX = mainLayoutWidth - menuRightMargin - contentXOffset;
   }
   content.offsetLeftAndRight(diffX);
   contentXOffset += diffX;
   this.invalidate();

   prevX = curX;
   lastDiffX = diffX;
   return true;

  case MotionEvent.ACTION_UP:
   Log.d("MainLayout.java onContentTouch()", "Up lastDiffX "
     + lastDiffX);

   if (lastDiffX > 0) {
    currentMenuState = MenuState.SHOWING;
    menuScroller.startScroll(contentXOffset, 0,
      menu.getLayoutParams().width - contentXOffset, 0,
      SLIDING_DURATION);
   } else if (lastDiffX < 0) {
    currentMenuState = MenuState.HIDING;
    menuScroller.startScroll(contentXOffset, 0, -contentXOffset, 0,
      SLIDING_DURATION);
   }
   menuHandler.postDelayed(menuRunnable, QUERY_INTERVAL);
   this.invalidate();
   isDragging = false;
   prevX = 0;
   lastDiffX = 0;
   return true;

  default:
   break;
  }

  return false;
 }
}


Layout1.java

package com.android.slidingmenuexample;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Layout1 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_layout1, null);
        return view;
    }
}


Layout2.java

package com.android.slidingmenuexample;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Layout2 extends Fragment {

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {
  View view = inflater.inflate(R.layout.fragment_layout2, null);
  return view;
 }
}



activity_main.xml
<com.android.slidingmenuexample.MainLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    
     <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <ListView
            android:id="@+id/menu_listview"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:background="@android:color/holo_purple"
            android:cacheColorHint="#00000000" >
        </ListView>
    </LinearLayout>

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
  
        
        <LinearLayout
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:background="@android:color/darker_gray"
         android:orientation="horizontal" >
            
            <Button
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:onClick="toggleMenu"
             android:text="Menu"
             android:id="@+id/button_menu" />
            
            <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Layout 1"
        android:gravity="center"
        android:id="@+id/activity_main_content_title"
        android:layout_weight="1" />
            
        </LinearLayout>       
        
        
        <FrameLayout
      android:id="@+id/activity_main_content_fragment"
      android:layout_width="match_parent"
      android:layout_height="match_parent" >
        
     </FrameLayout>
        
    </LinearLayout>

</com.android.slidingmenuexample.MainLayout>


fragment_layout1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_blue_dark" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:text="Layout 1"
        android:textColor="@android:color/black"
        android:textSize="20sp" />

</RelativeLayout>


fragment_layout2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_green_dark"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Layout2"
        android:textColor="@android:color/black"
        android:textSize="20sp" />

</RelativeLayout>


rec/values/menu_items.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="menu_items">
        <item >Layout 1</item>
        <item >Layout 2</item>
    </string-array>
</resources>






Simple Navigation Drawer example in android

Complete project on GITHUB

I hope this post is useful. kindly share your feedback as comment here.


Thank You



Sunday, 6 October 2013

Send mail from Android application without using default/built-in application

We know, We can send an e-mail using Intents, This will invoke either default mail app or built-in device mail apps to send an e-mail. This is unnecessary for user to work on e-mail application while he is trying to work an our application. So the question is
how to send an e-mail from android application without user interaction?
Answer is you can achieve this using JavaMail API.
You have to use following three jars.
  1. mail.jar
  2. activation.jar
  3. additionnal.jar
Complete code:

MainActivity.java

package com.exmple.javamail;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MainActivity extends Activity {
 private static String username = "";
 private static String password = "";
 private static String name = "";
 private EditText mRecEmailEdit;
 private EditText mSubjectEdit;
 private EditText mMessageEdit;
 private EditText mNameEdit;
 private EditText mEmailEdit;
 private EditText mPasswordEdit;

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

  mNameEdit = (EditText) findViewById(R.id.sender_name);
  mEmailEdit = (EditText) findViewById(R.id.sender_email);
  mPasswordEdit = (EditText) findViewById(R.id.sender_password);
  mRecEmailEdit = (EditText) findViewById(R.id.email);
  mSubjectEdit = (EditText) findViewById(R.id.subject);
  mMessageEdit = (EditText) findViewById(R.id.message);
  Button sendButton = (Button) findViewById(R.id.send);

  sendButton.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
    name = mNameEdit.getText().toString();
    username = mEmailEdit.getText().toString();
    password = mPasswordEdit.getText().toString();
    String email = mRecEmailEdit.getText().toString();
    String subject = mSubjectEdit.getText().toString();
    String message = mMessageEdit.getText().toString();
    sendMail(email, subject, message);
   }
  });
 }

 private void sendMail(String email, String subject, String messageBody) {
  Session session = createSessionObject();

  try {
   Message message = createMessage(email, subject, messageBody,
     session);
   new SendMailTask().execute(message);
  } catch (AddressException e) {
   e.printStackTrace();
  } catch (MessagingException e) {
   e.printStackTrace();
  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
  }
 }

 private Message createMessage(String email, String subject,
   String messageBody, Session session) throws MessagingException,
   UnsupportedEncodingException {
  Message message = new MimeMessage(session);
  message.setFrom(new InternetAddress(username, name));
  message.addRecipient(Message.RecipientType.TO, new InternetAddress(
    email, email));
  message.setSubject(subject);
  message.setText(messageBody);
  return message;
 }

 private Session createSessionObject() {
  Properties properties = new Properties();
  properties.put("mail.smtp.auth", "true");
  properties.put("mail.smtp.starttls.enable", "true");
  properties.put("mail.smtp.host", "smtp.gmail.com");
  properties.put("mail.smtp.port", "587");

  return Session.getInstance(properties, new javax.mail.Authenticator() {
   protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(username, password);
   }
  });
 }

 private class SendMailTask extends AsyncTask<Message, Void, Void> {
  private ProgressDialog progressDialog;

  @Override
  protected void onPreExecute() {
   super.onPreExecute();
   progressDialog = ProgressDialog.show(MainActivity.this,
     "Please wait", "Sending mail", true, false);
  }

  @Override
  protected void onPostExecute(Void aVoid) {
   super.onPostExecute(aVoid);
   progressDialog.dismiss();
  }

  @Override
  protected Void doInBackground(Message... messages) {
   try {
    Transport.send(messages[0]);
    runOnUiThread(new Runnable() {

     @Override
     public void run() {
      Toast.makeText(MainActivity.this,
        "Mail sent successfully", Toast.LENGTH_LONG)
        .show();
     }
    });
   } catch (final MessagingException e) {
    e.printStackTrace();
    runOnUiThread(new Runnable() {

     @Override
     public void run() {
      Toast.makeText(MainActivity.this,
        e.getClass() + " : " + e.getMessage(),
        Toast.LENGTH_LONG).show();
     }
    });
   }
   return null;
  }
 }
}


activity_main.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: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/sender_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:ems="10"
        android:hint="your Name"
        android:inputType="textEmailAddress" />

    <EditText
        android:id="@+id/sender_email"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/sender_name"
        android:ems="10"
        android:hint="your e-mail"
        android:inputType="textEmailAddress" />

    <EditText
        android:id="@+id/sender_password"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/email"
        android:inputType="textPassword"
        android:layout_below="@+id/sender_email"
        android:hint="Your e-mail password" />

    <EditText
        android:id="@+id/email"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/sender_password"
        android:ems="10"
        android:hint="reciever e-mail"
        android:inputType="textEmailAddress" />

    <EditText
        android:id="@+id/subject"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/email"
        android:layout_below="@+id/email"
        android:hint="subject" />

    <EditText
        android:id="@+id/message"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/subject"
        android:ems="10"
        android:hint="message"
        android:inputType="textMultiLine"
        android:lines="5" />

    <Button
        android:id="@+id/send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/message"
        android:text="Send!" />

</RelativeLayout>




Complete code as zip on GITHUB

I hope this post is useful. kindly share your feedback as comment here.


Thank You



Thursday, 26 September 2013

Simple Example for extracting zip file in android

You can extract zip file by using
ZipInputStream
class in android.

MainActivity.java
package com.android.zipextracter;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;
import android.app.Activity;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  String zipFilePath = Environment.getExternalStorageDirectory()
    .getAbsolutePath()+"/";
  unpackZip(zipFilePath, "MyRar.zip");
 }

 private boolean unpackZip(String path, String zipname) {
  InputStream is;
  ZipInputStream zis;
  try {
   String filename;
   is = new FileInputStream(path + zipname);
   zis = new ZipInputStream(new BufferedInputStream(is));
   ZipEntry mZipEntry;
   byte[] buffer = new byte[1024];
   int count;

   while ((mZipEntry = zis.getNextEntry()) != null) {
    // zapis do souboru
    filename = mZipEntry.getName();

    // Need to create directories if not exists, or
    // it will generate an Exception...
    if (mZipEntry.isDirectory()) {
     File fmd = new File(path + filename);
     fmd.mkdirs();
     continue;
    }

    FileOutputStream fout = new FileOutputStream(path + filename);

    // cteni zipu a zapis
    while ((count = zis.read(buffer)) != -1) {
     fout.write(buffer, 0, count);
    }

    fout.close();
    zis.closeEntry();
    Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
   }

   zis.close();
  } catch (IOException e) {
   e.printStackTrace();
   return false;
  }

  return true;
 }
}


Don't forget to add following uses-permission in your manifest file


I hope this post is useful to you. kindly share your feedback as comment here.


Thank You



Friday, 20 September 2013

Custom DialogFragment Example in android

By this example you can access your DialogFragment throughout the application. You can send arguments to DialogFragment, and also you can retrieve values from DialogFragment.

Screenshot:


Code:

MyCustomDialog.java
package com.andoid.dialogfragment;

import android.app.Dialog;
import android.app.DialogFragment;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;

public class MyCustomDialog extends DialogFragment {
 Button mButton;
 EditText mEditText;
 onSubmitListener mListener;
 String text = "";

 interface onSubmitListener {
  void setOnSubmitListener(String arg);
 }

 @Override
 public Dialog onCreateDialog(Bundle savedInstanceState) {
  final Dialog dialog = new Dialog(getActivity());
  dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
  dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);
  dialog.setContentView(R.layout.custom_dialog);
  dialog.getWindow().setBackgroundDrawable(
    new ColorDrawable(Color.TRANSPARENT));
  dialog.show();
  mButton = (Button) dialog.findViewById(R.id.button1);
  mEditText = (EditText) dialog.findViewById(R.id.editText1);
  mEditText.setText(text);
  mButton.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    mListener.setOnSubmitListener(mEditText.getText().toString());
    dismiss();
   }
  });
  return dialog;
 }
}


custom_dialog.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:background="#efefef"
    android:gravity="center"
    android:orientation="vertical" >

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

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Submit" />

</LinearLayout>


Code for access this DialogFragment from our Activity
MainActivity.java
package com.andoid.dialogfragment;

import com.andoid.dialogfragment.MyCustomDialog.onSubmitListener;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;

public class MainActivity extends Activity implements onSubmitListener {
 TextView mTextView;
 Button mButton;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  mTextView = (TextView) findViewById(R.id.textView1);
  mButton = (Button) findViewById(R.id.button1);
  mButton.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {
    MyCustomDialog fragment1 = new MyCustomDialog(); 
    fragment1.mListener = MainActivity.this;
    fragment1.text = mTextView.getText().toString();
    fragment1.show(getFragmentManager(), "");
   }
  });  
  
 }

 @Override
 public void setOnSubmitListener(String arg) {
  mTextView.setText(arg);
 }

}


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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"        
        android:text="Change Text" />

</LinearLayout>



I hope this post is useful to you. kindly share your feedback as comment here.


Thank You



Thursday, 19 September 2013

Simple TextToSpeech Example in Android

Now possible to hear the spoken of words by Android.

Screenshot:

Code:

TextToSpeechActivity.java
package com.android.texttospeach;

import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.util.Locale;

public class TextToSpeechActivity extends Activity implements
  TextToSpeech.OnInitListener {

 private static final String TAG = "MyTextToSpeechDemo";

 private TextToSpeech mTts;
 private Button mPlayButton;
 EditText mEditText;

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

  // Initialize text-to-speech. This is an asynchronous operation.
  mTts = new TextToSpeech(this, this);

  mPlayButton = (Button) findViewById(R.id.button1);
  mEditText = (EditText) findViewById(R.id.editText1);
  mPlayButton.setOnClickListener(new View.OnClickListener() {
   public void onClick(View v) {
    play();
   }
  });
 }

 @Override
 public void onDestroy() {
  // Don't forget to shutdown!
  if (mTts != null) {
   mTts.stop();
   mTts.shutdown();
  }

  super.onDestroy();
 }

 // Implements TextToSpeech.OnInitListener.
 public void onInit(int status) {
  // status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR.
  if (status == TextToSpeech.SUCCESS) {
   int result = mTts.setLanguage(Locale.US);
   if (result == TextToSpeech.LANG_MISSING_DATA
     || result == TextToSpeech.LANG_NOT_SUPPORTED) {
    Log.e(TAG, "Language is not available.");
   } else {
    mPlayButton.setEnabled(true);
    play();
   }
  } else {
   Log.e(TAG, "Could not initialize TextToSpeech.");
  }
 }

 private void play() {
  String hello = mEditText.getText().toString();
  mTts.speak(hello, TextToSpeech.QUEUE_FLUSH, null);
 }

}


text_to_speech.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="vertical" >

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

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:enabled="false"   
        android:ems="7"
        android:gravity="center"    
        android:text="Play" />

</LinearLayout>
I hope this post is useful to you. kindly share your feedback as comment here.



Thank You



Sunday, 1 September 2013

Spinner with multiple selection in Android

Video Output:



Source code link is added below.

Here we have a class called MultiSelectionSpinner.

In this class we have following methods.


  • public void setItems(String[] items)


    Used to set adapter items using array of strings to this spinner.
  • public void setItems(List items)


    Used to set adapter items using list of strings to this spinner.
  • public void setSelection(String[] selection)


    Used to set selected items on this adapter using array of strings to this spinner.
  • public void setSelection(List selection)


    Used to set selected items on this adapter using list of strings to this spinner.
  • public void setSelection(int index)


    Used to set single selected item using position to this spinner.
  • public void setSelection(int[] selectedIndices)


    Used to set selected items using array of integers to this spinner.
  • public List getSelectedStrings()


    Used to get the selected items as a string
  • public List getSelectedIndices()


    Used to get the selected indexes as a list of integers


  • I hope this post is useful to you. kindly share your feedback as comment here.



    Source code on GitHub



    Thank You



    Sunday, 25 August 2013

    Simple SQLiteHelper example in android



    SQLiteHelper.jar

    This jar has the following functions.

    1. public SQLiteHelper(Context context, String dbname, CursorFactory factory, int version)
    This constructor is used to initialize SQLiteOpenHelper class.

    2. public void createTable(String table_name, String[] fields, String[] types)
    This method is used to create table with fields. Total number of fields and types must be equal.

    3. public ArrayList<HashMap<String, Object>> getFields(String table_name)
    This method will return all fields with their types as ArrayList.

    4. public String insertData(String table_name, String[] fields, String[] data)
    This method used to insert record in our table. This will return a String as
    Transaction successfully completed
    if the transaction completed. Otherwise it will return exception.

    5. public ArrayList<HashMap<String, Object>> getAllData(String table_name)
    This method used to get all record from our table as arraylist.

    6. public ArrayList<HashMap<String, Object>> getSelectedData(String table_name, String fields[], String[] WhereClolmn, String[] WhereClolmnType, String[] data)
    This method will return selected data as ArrayList

    7. public String UpdateData(String table_name, String[] fields, String[] data, String WHereClassField, String WhereClassFieldData)
    This method used to update record in our table. This will return a String as
    Transaction Successfully Updated
    if the transaction completed. Otherwise it will return exception.

    8. public String deleteRecords(String table_name, String field_name, String[] data)
    This method used to delete record in our table. This will return a String as
    Number of rows deleted


    9. public void addFields(String table_name, String field_name, String type, String defaultValue)
    This method used to add new field in our table

    10. public String executeQuery(String query)
    This method used to execute the dynamic query

    Sample program using this jar

    MainActivity.java

    package com.example.myproject;
    
    import com.example.dbhelper.SQLiteHelper;
    
    import android.os.Bundle;
    import android.app.Activity;
    import android.content.Context;
    import android.database.sqlite.SQLiteDatabase.CursorFactory;
    
    public class MainActivity extends Activity {
    
     SQLiteHelper helper;
     Context context;
     String DBName;
     CursorFactory factory = null;
     int version = 1;
    
     @Override
     protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      context = this;
      DBName = "MyDBname";
      helper = new SQLiteHelper(context, DBName, factory, version);
      helper.createTable("MyFirstTable", new String[] { "id", "name" },
        new String[] { "INTEGER PRIMARY KEY AUTOINCREMENT", "TEXT" });
      System.out.println(helper.getFields("MyFirstTable"));
      System.out.println(helper.insertData("MyFirstTable",
        new String[] { "name" }, new String[] { "Gunaseelan" }));
      System.out.println(helper.getAllData("MyFirstTable"));
      System.out.println(helper.UpdateData("MyFirstTable",
        new String[] { "name" }, new String[] { "Guna" }, "name",
        "Gunaseelan"));
      System.out.println(helper.getAllData("MyFirstTable"));
      System.out.println(helper.deleteRecords("MyFirstTable", "name",
        new String[] { "Guna" }));
      System.out.println(helper.getAllData("MyFirstTable"));
      
      helper.addFields("MyFirstTable", "mark", "NUMBER", "");
      
      System.out.println(helper.insertData("MyFirstTable", new String[] {
        "name", "mark" }, new String[] { "Gunaseelan", "98" }));
      System.out.println(helper.getSelectedData("MyFirstTable", new String[] {
        "name", "mark" }, new String[] { "name", "mark" },
        new String[] { "Text", "Number" }, new String[] { "Gunaseelan",
          "98" }));
      System.out.println(helper.executeQuery("Select * from MyFirstTable"));
     }
    }
    
    Logcat output

    [{Type=INTEGER, Filed=id}, {Type=TEXT, Filed=name}, {Type=NUMBER, Filed=mark}]
    Transaction successfully completed
    [{id=4, mark=, name=Gunaseelan}]
    Transaction Successfully Updated
    [{id=4, mark=, name=Guna}]
    Number of rows deleted 1
    Transaction successfully completed
    [{mark=98, name=Gunaseelan}]
    I hope this post will help you. kindly share your feedback and suggestion as comment.



    Thank You



    Wednesday, 31 July 2013

    Simple ListFragment Example in Android

    This post will help you to create simple ListFragment in android.

    MainActivity.java

    package com.example.listfragmentexample;
    
    import android.os.Bundle;
    import android.app.Activity;
    import android.app.FragmentManager;
    import android.app.ListFragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    
    public class MainActivity extends Activity {
    
     @Override
     protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
    
      FragmentManager fm = getFragmentManager();
    
      if (fm.findFragmentById(android.R.id.content) == null) {
       SimpleListFragment list = new SimpleListFragment();
       fm.beginTransaction().add(android.R.id.content, list).commit();
      }
     }
    
     public static class SimpleListFragment extends ListFragment
     {
    
      String[] numbers_text = new String[] { "one", "two", "three", "four",
        "five", "six", "seven", "eight", "nine", "ten", "eleven",
        "twelve", "thirteen", "fourteen", "fifteen" };
      String[] numbers_digits = new String[] { "1", "2", "3", "4", "5", "6", "7",
        "8", "9", "10", "11", "12", "13", "14", "15" };
    
      @Override
      public void onListItemClick(ListView l, View v, int position, long id) {
       new CustomToast(getActivity(), numbers_digits[(int) id]);   
      }
    
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
       ArrayAdapter<String> adapter = new ArrayAdapter<String>(
         inflater.getContext(), android.R.layout.simple_list_item_1,
         numbers_text);
       setListAdapter(adapter);
       return super.onCreateView(inflater, container, savedInstanceState);
      }
     }
    }
    


    Screen Shot:



    Just have a look on here to CustomToast. This CustomToast is created by using Dialog class in android.

    1. Simple Fragments with Action Bar Example in Android

    2. ListFragments in Android with simple example

    3. Simple Fragment Example in Android

    4. Simple RecyclerView Example in Android



    Thank You



    Simple Fragment Example in Android

    This post will help you to create simple Fragment in android.

    MainActivity.java

    package com.simple.sfragmentexample;
    
    import android.os.Bundle;
    import android.app.Activity;
    import android.app.Fragment;
    import android.app.FragmentTransaction;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    
    public class MainActivity extends Activity {
     int i = 1;
    
     @Override
     protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
    
      setContentView(R.layout.fragment_simple);
      if (savedInstanceState == null) {
       Fragment newFragment = SimpleAddition.newInstance(i);
       FragmentTransaction ft = getFragmentManager().beginTransaction();
       ft.add(R.id.FrameLayout1, newFragment).commit();
      } else {
       i = savedInstanceState.getInt("level");
      }
     }
    
     @Override
     public void onSaveInstanceState(Bundle outState) {
      super.onSaveInstanceState(outState);
      outState.putInt("level", i);
     }
    
     public static class SimpleAddition extends Fragment {
      int mNum;
    
      static SimpleAddition newInstance(int num) {
       SimpleAddition f = new SimpleAddition();
    
       Bundle args = new Bundle();
       args.putInt("num", num);
       f.setArguments(args);
    
       return f;
      }
      
      @Override
      public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       mNum = getArguments() != null ? getArguments().getInt("num") : 1;
      }
      
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
       View v = inflater.inflate(R.layout.activity_main, container, false);
       
       Button b = (Button) v.findViewById(R.id.button1);
       final EditText et1 = (EditText) v.findViewById(R.id.editText1);   
       final TextView tv = (TextView) v.findViewById(R.id.textView1);
    
       b.setOnClickListener(new OnClickListener() {
    
        @Override
        public void onClick(View v) {        
         tv.setText(et1.getText().toString());
        }
       });   
       return v;
      }
     }
    
    }
    


    fragment_simple.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:gravity="center_horizontal"
        android:orientation="vertical"
        android:padding="4dip" >
    
        <FrameLayout
            android:id="@+id/FrameLayout1"
            android:layout_width="match_parent"
            android:layout_height="0px"
            android:layout_weight="1" >
        </FrameLayout>
    
    </LinearLayout>
    


    activity_main.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: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/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/hello_world" />
    
        <EditText
            android:id="@+id/editText1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/textView1"
            android:layout_below="@+id/textView1"
            android:layout_marginTop="22dp"
            android:ems="10" >
    
            <requestFocus />
        </EditText>
    
        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/editText1"
            android:layout_below="@+id/editText1"
            android:layout_marginTop="28dp"
            android:text="Button" />
    
    </RelativeLayout>
    


    Screen Shot:



    1. Simple Fragments with Action Bar Example in Android

    2. ListFragments in Android with simple example

    3. Simple ListFragment Example in Android

    I hope this post is useful to you. kindly share your feedback as comment here.



    Thank You



    Sunday, 14 July 2013

    Simple Fragments with Action Bar Example in Android


    A Fragment represents a behavior of user interface in an Activity. A activity can have more than one fragments and also a fragment can be used in more than one activities.

    Screen Shots of following tutorial.
    Fragment 1



    Fragment 2



    See, Here I have used the Action Bar to navigate between tabs. Which were added in Android 3.0 (API level 11). So in lower version Action Bar doesn't work. You can take this post as Simple Action Bar tutorial in Android too :)

    Following class works as a home for those two Fragments.
    FragmentTabs.java

    package com.example.fragmentexample;
    
    import android.app.ActionBar;
    import android.app.ActionBar.Tab;
    import android.app.Activity;
    import android.app.Fragment;
    import android.app.FragmentTransaction;
    import android.os.Bundle;
    
    public class FragmentTabs extends Activity {
     @Override
     protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
    
      final ActionBar bar = getActionBar();
      bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
      bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
    
      bar.addTab(bar
        .newTab()
        .setText("Simple")
        .setTabListener(
          new TabListener<FragmentCalculate.SimpleAddition>(this,
            "simple", FragmentCalculate.SimpleAddition.class)));
      bar.addTab(bar
        .newTab()
        .setText("List")
        .setTabListener(
          new TabListener<SampleList.SampleListFragment>(
            this, "list",
            SampleList.SampleListFragment.class)));
      if (savedInstanceState != null) {
       bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
      }
     }
    
     @Override
     protected void onSaveInstanceState(Bundle outState) {
      super.onSaveInstanceState(outState);
      outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
     }
    
     public static class TabListener<T extends Fragment> implements
       ActionBar.TabListener {
      private final Activity mActivity;
      private final String mTag;
      private final Class<T> mClass;
      private final Bundle mArgs;
      private Fragment mFragment;
    
      public TabListener(Activity activity, String tag, Class<T> clz) {
       this(activity, tag, clz, null);
      }
    
      public TabListener(Activity activity, String tag, Class<T> clz,
        Bundle args) {
       mActivity = activity;
       mTag = tag;
       mClass = clz;
       mArgs = args;
    
       mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag);
       if (mFragment != null && !mFragment.isDetached()) {
        FragmentTransaction ft = mActivity.getFragmentManager()
          .beginTransaction();
        ft.detach(mFragment);
        ft.commit();
       }
      }
    
      public void onTabSelected(Tab tab, FragmentTransaction ft) {
       if (mFragment == null) {
        mFragment = Fragment.instantiate(mActivity, mClass.getName(),
          mArgs);
        ft.add(android.R.id.content, mFragment, mTag);
       } else {
        ft.attach(mFragment);
       }
      }
    
      public void onTabUnselected(Tab tab, FragmentTransaction ft) {
       if (mFragment != null) {
        ft.detach(mFragment);
       }
      }
    
      public void onTabReselected(Tab tab, FragmentTransaction ft) {
       new CustomToast(mActivity, "Reselected!");
      }
     }
    }
    


    Following program creates the first Fragment.
    FragmentCalculate.java

    package com.example.fragmentexample;
    
    import android.app.Activity;
    import android.app.Fragment;
    import android.app.FragmentTransaction;
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    
    public class FragmentCalculate extends Activity {
     int i = 1;
    
     @Override
     protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
    
      if (savedInstanceState == null) {
       Fragment newFragment = SimpleAddition.newInstance(i);
       FragmentTransaction ft = getFragmentManager().beginTransaction();
       ft.add(R.id.FrameLayout1, newFragment).commit();
      } else {
       i = savedInstanceState.getInt("level");
      }
     }
    
     @Override
     public void onSaveInstanceState(Bundle outState) {
      super.onSaveInstanceState(outState);
      outState.putInt("level", i);
     }
    
     public static class SimpleAddition extends Fragment {
      int mNum;
    
      static SimpleAddition newInstance(int num) {
       SimpleAddition f = new SimpleAddition();
    
       Bundle args = new Bundle();
       args.putInt("num", num);
       f.setArguments(args);
    
       return f;
      }
      
      @Override
      public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       mNum = getArguments() != null ? getArguments().getInt("num") : 1;
      }
      
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
       View v = inflater.inflate(R.layout.addition, container, false);
       
       Button b = (Button) v.findViewById(R.id.button1);
       final EditText et1 = (EditText) v.findViewById(R.id.editText1);
       final EditText et2 = (EditText) v.findViewById(R.id.editText2);
       final TextView tv = (TextView) v.findViewById(R.id.textView1);
    
       b.setOnClickListener(new OnClickListener() {
    
        @Override
        public void onClick(View v) {
         int a = Integer.parseInt(et1.getText().toString());
         int b = Integer.parseInt(et2.getText().toString());
         tv.setText("  Total = "+String.valueOf(a+b));
        }
       });
       
       return v;
      }
     }
    
    }
    
    


    Following program creates the second Fragment.
    FragmentCalculate.java

    package com.example.fragmentexample;
    
    import android.app.Activity;
    import android.app.FragmentManager;
    import android.app.ListFragment;
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    
    public class SampleList extends Activity {
    
     @Override
     protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
    
      FragmentManager fm = getFragmentManager();
    
      if (fm.findFragmentById(android.R.id.content) == null) {
       SampleListFragment list = new SampleListFragment();
       fm.beginTransaction().add(android.R.id.content, list).commit();
      }
     }
    
     public static class SampleListFragment extends ListFragment
     {
    
      String[] numbers_text = new String[] { "one", "two", "three", "four",
        "five", "six", "seven", "eight", "nine", "ten", "eleven",
        "twelve", "thirteen", "fourteen", "fifteen" };
      String[] numbers_digits = new String[] { "1", "2", "3", "4", "5", "6", "7",
        "8", "9", "10", "11", "12", "13", "14", "15" };
    
      @Override
      public void onListItemClick(ListView l, View v, int position, long id) {
       new CustomToast(getActivity(), numbers_digits[(int) id]);   
      }
    
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
       ArrayAdapter<String> adapter = new ArrayAdapter<String>(
         inflater.getContext(), android.R.layout.simple_list_item_1,
         numbers_text);
       setListAdapter(adapter);
       return super.onCreateView(inflater, container, savedInstanceState);
      }
     }
    }
    


    Layout design for first child.
    addition.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="vertical" >
    
        <EditText
            android:id="@+id/editText1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="number" >
    
            <requestFocus />
        </EditText>
    
        <EditText
            android:id="@+id/editText2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="number" />
    
        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="ADD" />
    
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />
    
    </LinearLayout>
    


    Layout which contains FrameLayout1
    addition.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:gravity="center_horizontal"
        android:orientation="vertical"
        android:padding="4dip" >
    
        <FrameLayout
            android:id="@+id/FrameLayout1"
            android:layout_width="match_parent"
            android:layout_height="0px"
            android:layout_weight="1" >
        </FrameLayout>
    
    </LinearLayout>
    


    Source code on GITHUB

    1.ListFragments in Android with simple example

    2.Simple Fragment Example in Android

    3. Simple ListFragment Example in Android

    Just have a look on here to CustomToast. This CustomToast is created by using Dialog class in android.

    I hope this post is useful to you. kindly share your feedback as comment here.



    Thank You



    Tuesday, 2 July 2013

    Change spinner text color by button click

    We can change the color of spinner text by click the button. Following four steps will explain it clearly.
    1. Create a xml named spinnertext.xml in res/layout folder. Here we customize the text of spinner.

    spinnertext.xml
    
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/spinnerText"
        style="?android:attr/spinnerItemStyle"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:paddingBottom="2dp"
        android:paddingLeft="6dp"
        android:textColor="#662293" />
    

    2. Create a xml named spinner_selector.xml in res/layout folder. Here we customize the spinner drop down menu.

    spinner_selector.xml
    
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        style="?android:attr/spinnerItemStyle"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:textColor="#000000" />
    

    3. Now main.xml. Here I get the togglebutton to change the color.

    main.xml
    
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
    
        <ToggleButton
            android:id="@+id/toggleButton1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="ToggleButton" />
    
        <Spinner
            android:id="@+id/spinner1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    
    </LinearLayout>
    

    4. Now in code we can work with toggle button to change the color.

    code for toggle buttton
    ToggleButton mToggleButton = (ToggleButton) findViewById(R.id.toggleButton1);
       mToggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    
           @Override
           public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
               TextView tv = (TextView) findViewById(R.id.spinnerText);
               if (isChecked)
                   tv.setTextColor(Color.BLUE);
               else
                   tv.setTextColor(Color.RED);
    
           }
    });
    

    code for spinner adapter
    String array[] = { "one", "two", "three" };
    ArrayAdapter sp_adapter = new ArrayAdapter(this, R.layout.spinnertext, array);
    sp_adapter.setDropDownViewResource(R.layout.spinner_selector);
    Spinner sp = (Spinner) findViewById(R.id.spinner1);
    sp.setAdapter(sp_adapter);
    


    complete code
    SpinnerTextActivity.java
    package com.example.spinnertext;
    
    import android.app.Activity;
    import android.graphics.Color;
    import android.os.Bundle;
    import android.widget.ArrayAdapter;
    import android.widget.CompoundButton;
    import android.widget.CompoundButton.OnCheckedChangeListener;
    import android.widget.Spinner;
    import android.widget.TextView;
    import android.widget.ToggleButton;
    
    public class SpinnerTextActivity extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            
            ToggleButton mToggleButton = (ToggleButton) findViewById(R.id.toggleButton1);
            mToggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    
                @Override
                public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
                    TextView tv = (TextView) findViewById(R.id.spinnerText);
                    if (isChecked)
                        tv.setTextColor(Color.BLUE);
                    else
                        tv.setTextColor(Color.RED);
    
                }
            });
            
            String array[] = { "one", "two", "three" };
            ArrayAdapter<String> sp_adapter = new ArrayAdapter<String>(this, R.layout.spinnertext, array);
            sp_adapter.setDropDownViewResource
            (R.layout.spinner_selector);
            Spinner sp = (Spinner) findViewById(R.id.spinner1);
            sp.setAdapter(sp_adapter);
        }
    }
    


    Screen shot 1. (ToggleButton is ON)



    Screen shot 2. (ToggleButton is OFF)



    Thank You



    Sunday, 30 June 2013

    Return values from custom popup window to activity

    We can return values from custom popup window to activity using listener. Example code:

    popup.xml
    
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#cdcdcd"
        android:gravity="center"
        android:orientation="vertical"
        android:padding="50dp" >
    
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp" />
    
        <EditText
            android:id="@+id/bank_name"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="3dp"
            android:hint="Name"
            android:inputType="textCapWords" />
    
        <EditText
            android:id="@+id/bankacc_no"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="3dp"
            android:hint="Number"
            android:inputType="number" />
    
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="10dp" >
    
            <Button
                android:id="@+id/popupSave"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:padding="10dp"
                android:text="Save" />
    
            <Button
                android:id="@+id/popupClose"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:padding="10dp"
                android:text="Cancel" />
        </LinearLayout>
    
    </LinearLayout>
    


    Popup.java
    package com.example.popupwindow;
    
    import android.content.Context;
    import android.view.Gravity;
    import android.view.LayoutInflater;
    import android.view.MotionEvent;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.view.View.OnTouchListener;
    import android.view.WindowManager;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.PopupWindow;
    
    public class Popup extends PopupWindow {
    
    Context context;
    EditText et_name, et_number;
    String name, number;
    
    private int dx;
    private int dy;
    private OnSubmitListener mListener;
    
    public Popup(Context ctx, OnSubmitListener listener) {
    super(ctx);
    
    context = ctx;
    mListener = listener;
    
    setContentView(LayoutInflater.from(context).inflate(R.layout.popup, null));
    setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
    setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
    View popupView = getContentView();
    setFocusable(true);
    
    Button btn_close = (Button) popupView.findViewById(R.id.popupClose);
    Button btn_submit = (Button) popupView.findViewById(R.id.popupSave);
    et_name = (EditText) popupView.findViewById(R.id.bank_name);
    et_number = (EditText) popupView.findViewById(R.id.bankacc_no);
    
    btn_submit.setOnClickListener(new OnClickListener() {
    
    public void onClick(View v) {
    String name = et_name.getText().toString();
    String number = et_number.getText().toString();
    
    mListener.valueChanged(name, number);//To change the value of the textview of activity.
    dismiss();
    }
    });
    
    btn_close.setOnClickListener(new OnClickListener() {
    
    public void onClick(View arg0) {
    dismiss();
    }
    });
    
    // setOnTouchListener is to add drag and drop the popup window.
    // If you didn't want, you can remove it.
    popupView.setOnTouchListener(new OnTouchListener() {
    
    public boolean onTouch(View arg0, MotionEvent motionEvent) {
    switch (motionEvent.getAction()) {
    
    case MotionEvent.ACTION_DOWN:
    dx = (int) motionEvent.getRawX();
    dy = (int) motionEvent.getRawY();
    break;
    
    case MotionEvent.ACTION_MOVE:
    int x = (int) motionEvent.getRawX();
    int y = (int) motionEvent.getRawY();
    int left = (x - dx);
    int top = (y - dy);
    update(left, top, -1, -1);
    break;
    }
    return true;
    }
    });
    }
    
    public void show(View v) {
    showAtLocation(v, Gravity.CENTER, 0, 0);
    }
    
    public interface OnSubmitListener {
    void valueChanged(String name, String number);
    }
    }
    


    main.xml
    
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"   
        android:orientation="vertical" >
    
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Name" />
    
        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Number" />
    
        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="showPopup"
            android:text="Change" />
    
    </LinearLayout>


    To change the text of textview we have to implement OnSubmitListener in our activity.

    Also I have added my custom toast as DialogToast here. This toast message will disappear when you touch the screen and also when this custom toast message appears screen will goes to dim to view the toast message to user perfectly. If you didn't want just change the line to normal toast message or else you can remoe it.

    CustomPopupWindowActivity.java
    package com.example.popupwindow;
    
    import com.example.popupwindow.Popup.OnSubmitListener;
    
    import android.app.Activity;
    import android.content.Context;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.TextView;
    
    public class CustomPopupWindowActivity extends Activity implements OnSubmitListener {
    
    Context context;
    Popup popup;
    
    TextView mTextView1, mTextView2;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    
    mTextView1 = (TextView) findViewById(R.id.textView1);
    mTextView2 = (TextView) findViewById(R.id.textView2);
    
    context = this;
    popup = new Popup(context, this);
    }
    
    public void showPopup(View v) {
    popup.show(v);
    }
    
    @Override
    public void valueChanged(String name, String number) {
    mTextView1.setText(name);
    mTextView2.setText(number);
    new DialogToast(context, "Values updated").show();//For custom toast. You can change or remove this line.
    }
    }
    

    Sample screen shot of this code.



    Thank You



    Saturday, 22 June 2013

    Dialog as Toast message in Android


    What is toast message?

             In Adnroid, Toast is a notification message that pop up and display a cirtain amount of time.

    What is drawback toast message?

             Toast message should displayed cirtain amount of time. We can not interrupt it within the time. For example if we set a toast message to display five seconds, we can not hide it within two or three seconds. Tha is main drawback of Toast message.

    How to avercome this drawback?

             We can use Dialog as toast message in android. There is two main advantages by using Dialog as Toast message.
            1. We can hide the Toast message any time by touching the screen.
            2. While dispaly Toast message the background will goes to dim. So user can read the toast message without interruption of other views.

    DialogToast.java

    import android.app.Dialog;
    import android.content.Context;
    import android.os.Handler;
    import android.view.Gravity;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.Window;
    import android.widget.TextView;
    
    public class CustomToast extends Dialog {
     public CustomToast(Context context, String text) {
      super(context);
      requestWindowFeature(Window.FEATURE_NO_TITLE);
      LayoutInflater inflater = (LayoutInflater) context
      .getSystemService(android.content.Context.
         LAYOUT_INFLATER_SERVICE);
    
      View layout = inflater.inflate(R.layout.toast, null);
      TextView tv = (TextView) layout.findViewById(R.id.toastText);
      tv.setText(text);  
      setContentView(layout);
      show();
      setCanceledOnTouchOutside(true);
      setCancelable(true);
      Window window = getWindow();
      window.setGravity(Gravity.BOTTOM);
      new Handler().postDelayed(new Runnable() {
    
       public void run() {
        dismiss();
       }
      }, 2500);
     }
    }
    


    toast.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
    
        <TextView
            android:id="@+id/toastText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#000" />
    
    </LinearLayout>
    


    How to call this Dialog as Toast message?
             Following will allow you to display the Dialog as Toast message.
    new CustomToast(activity, "Custom Toast").show();
    

    Sample code to calling this Dialog as Toast message.

    DialogToastActivity.java
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    
    public class DialogToastActivity extends Activity {
     
     Activity activity;
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            activity = this;     
        }
        public void mButtonClick(View v){
         new CustomToast(activity, "Custom Toast").show();
        }
    }
    

    Screen shot.



    Thank You



    Thursday, 20 June 2013

    Drawing Example in Android

    Simple drawing example in android.

    In Android You can draw using Canvas. First You have to get the touched points to draw. By using onTouchEvent method You can get the touched points from android device. Our onTouchEvent method will be

    public boolean onTouchEvent(MotionEvent event) {
       PathWithPaint pp = new PathWithPaint();
       if (event.getAction() == MotionEvent.ACTION_DOWN) {
        path.moveTo(event.getX(), event.getY());
        path.lineTo(event.getX(), event.getY());
       } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
        path.lineTo(event.getX(), event.getY());
       } else if (event.getAction() == MotionEvent.ACTION_UP) {
        path.lineTo(event.getX(), event.getY());
        mCanvas.drawPath(path, mPaint);
        pp.setPath(path);
        pp.setmPaint(mPaint);
        _graphics1.add(pp);
       }
       invalidate();
       return true;
      }
    

    Now You are going to draw on the touched point. You have to override the onDraw method to draw on the path. The onDraw method will be like as following
      @Override
      public void onDraw(Canvas canvas) {
    
       canvas.drawBitmap(mBitmap, 0, 0, mPaint);
    
       if (_graphics1.size() > 0) {
        canvas.drawPath(_graphics1.get(_graphics1.size() - 1).getPath(), _graphics1.get(_graphics1.size() - 1).getmPaint());
       }
      }
    


    You can use ColorPicker to get different colors.

    Also you can save our drawing as .JPG file using FileOutputStream. Also you can erase previously drawn path and clear the whole drawing. And also you can set border.

    Complete Code.

    MainActivity.java
    package com.example.draw;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.util.ArrayList;
    import java.util.Date;
    
    import com.example.draw.ColorPicker.OnColorChangedListener;
    import android.app.Activity;
    import android.app.WallpaperManager;
    import android.content.Context;
    import android.graphics.Bitmap;
    import android.graphics.Bitmap.CompressFormat;
    import android.graphics.drawable.ShapeDrawable;
    import android.graphics.drawable.shapes.RoundRectShape;
    import android.graphics.BlurMaskFilter;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.ComposePathEffect;
    import android.graphics.CornerPathEffect;
    import android.graphics.DiscretePathEffect;
    import android.graphics.EmbossMaskFilter;
    import android.graphics.LinearGradient;
    import android.graphics.MaskFilter;
    import android.graphics.Paint;
    import android.graphics.Path;
    import android.graphics.PathEffect;
    import android.graphics.PorterDuff;
    import android.graphics.PorterDuffXfermode;
    import android.graphics.RectF;
    import android.graphics.Shader;
    import android.graphics.SweepGradient;
    import android.os.Bundle;
    import android.os.Environment;
    import android.util.Log;
    import android.view.Display;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.MotionEvent;
    import android.view.SubMenu;
    import android.view.View;
    import android.view.ViewGroup.LayoutParams;
    import android.view.Window;
    import android.widget.LinearLayout;
    import android.widget.Toast;
    
    public class MainActivity extends Activity implements OnColorChangedListener {
    
     @Override
     public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      requestWindowFeature(Window.FEATURE_NO_TITLE);
      setContentView(R.layout.activity_main);
      
      float[] outerR = new float[] { 12, 12, 12, 12, 0, 0, 0, 0 };
      RectF inset = new RectF(6, 6, 6, 6);
      float[] innerR = new float[] { 12, 12, 0, 0, 12, 12, 0, 0 };
      
      mDrawables = new ShapeDrawable[2];
      
      mDrawables[0] = new ShapeDrawable(new RoundRectShape(outerR, inset, null));
      mDrawables[0].getPaint().setShader(makeSweep());
      
      mDrawables[1] = new ShapeDrawable(new RoundRectShape(outerR, inset, innerR));
      mDrawables[1].getPaint().setShader(makeLinear());
      
      PathEffect mPathEffect1 = new DiscretePathEffect(10, 4);
      PathEffect mPathEffect2 = new CornerPathEffect(4);
      
      mDrawables[0].getPaint().setPathEffect(new ComposePathEffect(mPathEffect2, mPathEffect1));
      LinearLayout layout = (LinearLayout) findViewById(R.id.myDrawing);
      layout.setBackgroundDrawable(mDrawables[0]);
      activity = this; 
      mView = new DrawingView(this);
      layout.addView(mView, new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
      
      init();
      
      mEmboss = new EmbossMaskFilter(new float[] { 1, 1, 1 }, 0.4f, 6, 3.5f);
      mBlur = new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL);
     }
    
     private static Shader makeLinear() {
      return new LinearGradient(0, 0, 50, 50, new int[] { 0xFFFF0000, 0xFF00FF00, 0xFF0000FF }, null, Shader.TileMode.MIRROR);
     }
    
     private static Shader makeSweep() {
      return new SweepGradient(150, 25, new int[] { 0xFFFF0000, 0xFF00FF00, 0xFF0000FF, 0xFFFF0000 }, null);
     }
    
     private ShapeDrawable[] mDrawables;
     private MaskFilter mEmboss;
     private MaskFilter mBlur;
     private Paint mPaint;
     Activity activity;
     View mView;
    
     private void init() {
      mPaint = new Paint();
      mPaint.setDither(true);
      mPaint.setColor(0xFFFFFF00);
      mPaint.setStyle(Paint.Style.STROKE);
      mPaint.setStrokeJoin(Paint.Join.ROUND);
      mPaint.setStrokeCap(Paint.Cap.ROUND);
      mPaint.setStrokeWidth(3);
     }
    
     class DrawingView extends View {
      private Path path;
      private Bitmap mBitmap;
      private Canvas mCanvas;
      int width, height;
    
      public DrawingView(Context context) {
       super(context);
       path = new Path();
       mBitmap = Bitmap.createBitmap(820, 480, Bitmap.Config.ARGB_8888);
       mCanvas = new Canvas(mBitmap);
       this.setBackgroundColor(Color.BLACK);
      }
    
      private ArrayList<PathWithPaint> _graphics1 = new ArrayList<PathWithPaint>();
    
      public boolean onTouchEvent(MotionEvent event) {
       PathWithPaint pp = new PathWithPaint();
       if (event.getAction() == MotionEvent.ACTION_DOWN) {
        path.moveTo(event.getX(), event.getY());
        path.lineTo(event.getX(), event.getY());
       } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
        path.lineTo(event.getX(), event.getY());
       } else if (event.getAction() == MotionEvent.ACTION_UP) {
        path.lineTo(event.getX(), event.getY());
        mCanvas.drawPath(path, mPaint);
        pp.setPath(path);
        pp.setmPaint(mPaint);
        _graphics1.add(pp);
       }
       invalidate();
       return true;
      }
    
      @Override
      public void onDraw(Canvas canvas) {
    
       canvas.drawBitmap(mBitmap, 0, 0, mPaint);
    
       if (_graphics1.size() > 0) {
        canvas.drawPath(_graphics1.get(_graphics1.size() - 1).getPath(), _graphics1.get(_graphics1.size() - 1).getmPaint());
       }
       
       Display display = getWindowManager().getDefaultDisplay();
       int width = 300;
       int height = 425;
       try {
        Method mGetRawH = Display.class.getMethod("getRawHeight");
        Method mGetRawW = Display.class.getMethod("getRawWidth");
        width = (Integer) mGetRawW.invoke(display);
        height = (Integer) mGetRawH.invoke(display);
       } catch (SecurityException e) {
        e.printStackTrace();
       } catch (NoSuchMethodException e) {
        e.printStackTrace();
       } catch (IllegalArgumentException e) {
        e.printStackTrace();
       } catch (IllegalAccessException e) {
        e.printStackTrace();
       } catch (InvocationTargetException e) {
        e.printStackTrace();
       }
    
       int x = 0;
       int y = 0;
       if (curveDrawable == 1) {
        mDrawables[0].setBounds(x, y, x + width, (y + height) - 35);
        mDrawables[0].draw(canvas);
       }
       if (curveDrawable == 2) {
        mDrawables[1].setBounds(x, y, x + width, (y + height) - 35);
        mDrawables[1].draw(canvas);
       }
      }
    
      public void clearView() {
       _graphics1.removeAll(_graphics1);
       mBitmap = Bitmap.createBitmap(width, height,
         Bitmap.Config.ARGB_8888);
       mCanvas = new Canvas(mBitmap);
       path = new Path();
       invalidate();
      }
    
      @Override
      public void invalidate() {
       super.invalidate();
      }
    
      @Override
      protected void onSizeChanged(int w, int h, int oldw, int oldh) {
       super.onSizeChanged(w, h, oldw, oldh);
       width = w;
       height = h;
       mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
       mCanvas = new Canvas(mBitmap);
      }
    
      public void colorChange() {
       path = new Path();
       invalidate();
      }
    
      public void saveAsJpg(File f, View v, boolean setWallpaper) {
       String fname = f.getAbsolutePath();
       FileOutputStream fos = null;
       try {
        fos = new FileOutputStream(fname);
        Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
          Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        v.draw(c);
        
        if (setWallpaper) {
         WallpaperManager myWallpaperManager = WallpaperManager
           .getInstance(getApplicationContext());
         try {
          myWallpaperManager.setBitmap(b);
         } catch (IOException e) {
          e.printStackTrace();
         }
         Toast.makeText(activity, "Wallpaper has been seted up",
           Toast.LENGTH_LONG).show();
        } else {
         b.compress(CompressFormat.JPEG, 100, fos);
         Toast.makeText(activity, "Image Saved", Toast.LENGTH_LONG)
           .show();
        }
       } catch (Exception ex) {
        Toast.makeText(activity, "Error Saving Image",
          Toast.LENGTH_LONG).show();
        Log.i("DAVE", "stacktrace is " + ex);
       }
      }
     }
    
     private boolean isDrawBorder = true;
     int bgcolor = Color.BLACK;
    
     public void colorChanged(String key, int color) {
      
      if (key.equals("")) {
       mPaint = new Paint();
       mPaint.setDither(true);
       mPaint.setColor(color);
       mPaint.setStyle(Paint.Style.STROKE);
       mPaint.setStrokeJoin(Paint.Join.ROUND);
       mPaint.setStrokeCap(Paint.Cap.ROUND);
       mPaint.setStrokeWidth(3);
      } else if (key.equals("Bg Color")) {
       if (isDrawBorder)
        ((DrawingView) mView).invalidate();
       else
        ((DrawingView) mView).clearView();
       ((DrawingView) mView).setBackgroundColor(color);
       bgcolor = color;
       isDrawBorder = false;
      }
    
     }
    
     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
      super.onCreateOptionsMenu(menu);
    
      menu.add(0, 0, 0, "Color").setShortcut('3', 'c');
      menu.add(0, 1, 0, "BG Color").setShortcut('3', 'c');
      menu.add(0, 2, 0, "Emboss").setShortcut('4', 's');
      menu.add(0, 3, 0, "Blur").setShortcut('5', 'z');
      menu.add(0, 4, 0, "Erase").setShortcut('5', 'z');
      menu.add(0, 5, 0, "SrcATop").setShortcut('5', 'z');
      
      SubMenu border = menu.addSubMenu(0, 9, 0, "Border");
      
      menu.add(0, 6, 0, "Set as Wallpaper").setShortcut('5', 'z');
      menu.add(0, 7, 0, "Save").setShortcut('5', 'z');
      menu.add(0, 8, 0, "Clear").setShortcut('5', 'z');
    
      border.add(0, 10, 0, "Curve").setShortcut('5', 'z');
      border.add(0, 11, 0, "Rectangle").setShortcut('5', 'z');
      border.add(0, 12, 0, "No Border").setShortcut('5', 'z');
    
      return true;
     }
    
     private int curveDrawable = 1;
    
     @Override
     public boolean onOptionsItemSelected(MenuItem item) {
    
      File myDir = new File(Environment.getExternalStorageDirectory(),
        "Drawings");
      myDir.mkdirs();
      Date now = new Date();
      String fname = "image" + now.getDate() + now.getSeconds() + ".jpg";
      File file = new File(myDir, fname);
    
      switch (item.getItemId()) {
      
      case 0:
       ((DrawingView) mView).colorChange();
       new ColorPicker(activity, this, "", Color.BLUE, Color.WHITE).show();
       return true;
       
      case 1:
       new ColorPicker(activity, this, "Bg Color", Color.BLUE, Color.WHITE).show();
       return true;
       
      case 2:
       if (mPaint.getMaskFilter() != mEmboss) {
        mPaint.setMaskFilter(mEmboss);
       } else {
        mPaint.setMaskFilter(null);
       }
       return true;
       
      case 3:
       if (mPaint.getMaskFilter() != mBlur) {
        mPaint.setMaskFilter(mBlur);
       } else {
        mPaint.setMaskFilter(null);
       }
       return true;
       
      case 4:
       ((DrawingView) mView).colorChange();
       mPaint = new Paint();
       mPaint.setDither(true);
       mPaint.setColor(bgcolor);
       mPaint.setStyle(Paint.Style.STROKE);
       mPaint.setStrokeJoin(Paint.Join.ROUND);
       mPaint.setStrokeCap(Paint.Cap.ROUND);
       mPaint.setStrokeWidth(13);
       return true;
       
      case 5:
       mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP));
       mPaint.setAlpha(0x80);
       return true;
       
      case 6:
       ((DrawingView) mView).saveAsJpg(file, mView, true);
       return true;
       
      case 7:
       ((DrawingView) mView).saveAsJpg(file, mView, false);
       return true;
       
      case 8:
       ((DrawingView) mView).clearView();
       return true;
       
      case 10:
       isDrawBorder = true;
       colorChanged("Bg Color", bgcolor);
       curveDrawable = 1;
       return true;
       
      case 11:
       isDrawBorder = true;
       colorChanged("Bg Color", bgcolor);
       curveDrawable = 2;
       return true;
       
      case 12:
       isDrawBorder = true;
       colorChanged("Bg Color", bgcolor);
       curveDrawable = 0;
       return true;
       
      }
      return super.onOptionsItemSelected(item);
     }
    }
    

    PathWithPaint.java
    package com.example.draw;
    
    import android.graphics.Paint;
    import android.graphics.Path;
    
    public class PathWithPaint {
     private Path path;
    
     public Path getPath() {
      return path;
     }
    
     public void setPath(Path path) {
      this.path = path;
     }
     
     private Paint mPaint;
     
     public Paint getmPaint() {
      return mPaint;
     }
    
     public void setmPaint(Paint mPaint) {
      this.mPaint = mPaint;
     } 
    }
    


    Sample screen shot of this application


    Simple Drawing example in Android



    Thank You