<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>adblogcat.com</title>
	<atom:link href="http://adblogcat.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://adblogcat.com</link>
	<description>Learn Android</description>
	<lastBuildDate>Thu, 25 Apr 2013 01:02:22 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Fragment transition animations while hiding the previous fragment and using backstack</title>
		<link>http://adblogcat.com/fragment-transition-animations-while-hiding-the-previous-fragment/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=fragment-transition-animations-while-hiding-the-previous-fragment</link>
		<comments>http://adblogcat.com/fragment-transition-animations-while-hiding-the-previous-fragment/#comments</comments>
		<pubDate>Thu, 25 Apr 2013 00:37:43 +0000</pubDate>
		<dc:creator>guitarbaka</dc:creator>
				<category><![CDATA[Fragments]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[fragment]]></category>

		<guid isPermaLink="false">http://adblogcat.com/?p=458</guid>
		<description><![CDATA[This article will explain how to create fragments inside an Activity, how to dynamically add a fragment to an Activity, how to create transition animations between fragments, how to hide the previous fragment and finally how to use the fragment &#8230; <a href="http://adblogcat.com/fragment-transition-animations-while-hiding-the-previous-fragment/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="tall" count="1" href="http://adblogcat.com/fragment-transition-animations-while-hiding-the-previous-fragment/"></g:plusone></div><p id="top" /><a href="http://adblogcat.com/wp-content/uploads/2013/04/fragments.png"><img class="alignleft  wp-image-294" title="android_php_mysql" src="http://adblogcat.com/wp-content/uploads/2013/04/fragments.png" alt="" width="98" height="180" /></a>This article will explain how to create fragments inside an Activity, how to dynamically add a fragment to an Activity, how to create transition animations between fragments, how to hide the previous fragment and finally how to use the fragment backstack.<br />
<span id="more-458"></span><br />
You can download the code <a href="http://ece301-examples.googlecode.com/files/FragmentAnimation.zip">here</a></p>
<p>So first lets get started. We need to create three layout files, so create main.xml, fragment1.xml, fragment2.xml.<br />
main.xml:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:layout_width=&quot;wrap_content&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:background=&quot;#FFFFFF&quot; &gt;
    &lt;TextView android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot;
        android:text=&quot;Learning Fragments swap&quot; android:textColor=&quot;#800080&quot;
        android:textStyle=&quot;bold&quot;
        android:textSize=&quot;26sp&quot;&gt; &lt;/TextView&gt;
    &lt;FrameLayout
        android:id=&quot;@+id/fragment_swap&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:layout_height=&quot;fill_parent&quot; &gt;
    &lt;/FrameLayout&gt;

&lt;/RelativeLayout&gt;
</pre>
<p>We will be using the FrameLayout to do the fragment swaping.<br />
fragment1.xml:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:layout_width=&quot;wrap_content&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:layout_gravity=&quot;center&quot; &gt;

    &lt;ImageView
        android:id=&quot;@+id/adblogcat&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:src=&quot;@drawable/adblogcat&quot; &gt;
    &lt;/ImageView&gt;

    &lt;TextView
        android:id=&quot;@+id/fragment1&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_below=&quot;@id/adblogcat&quot;
        android:layout_centerInParent=&quot;true&quot;
        android:clickable=&quot;true&quot;
        android:gravity=&quot;center&quot;
        android:text=&quot;THIS IS FRAGMENT 1&quot;
        android:textColor=&quot;#FF0000&quot;
        android:textSize=&quot;30sp&quot;
        android:textStyle=&quot;bold&quot; &gt;
    &lt;/TextView&gt;

&lt;/RelativeLayout&gt;
</pre>
<p>fragment2.xml:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;TextView xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:id=&quot;@+id/fragment1&quot;
    android:layout_width=&quot;wrap_content&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:clickable=&quot;true&quot;
    android:gravity=&quot;center&quot;
    android:layout_gravity=&quot;center&quot;
    android:text=&quot;THIS IS FRAGMENT 2&quot;
    android:textColor=&quot;#000000&quot;
    android:textSize=&quot;30sp&quot; &gt;
&lt;/TextView&gt;
</pre>
<p>With fragment2, I want to show that you do not need a Layout View in an xml, you can inflate any View you want. In this case, a TextView.</p>
<p>Now we need to create a class Fragment1.java which extends Fragment. I have put comments in the code so its understandable, the code:</p>
<pre class="brush: java; title: ; notranslate">
public class Fragment1 extends Fragment {

	// my custom listener
	private OnFragment1ClickedListener mOnFragment1ClickedListener;

	// Must always call onCreateView and inflate your layout.
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		super.onCreateView(inflater, container, savedInstanceState);

		View view = inflater.inflate(R.layout.fragment1, container, false);

		// I want the whole view to be clickable, but I could have called the textView or ImageView only.
		view.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
                                // call the listener's abstract method, the implementation of the method happens in the Activity.
				mOnFragment1ClickedListener.onFragment1Clicked();
			}
		});

		return view;
	}

	// in onAttach we must instantiate the listener
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			mOnFragment1ClickedListener = (OnFragment1ClickedListener) activity;
		} catch (ClassCastException e) {
			e.printStackTrace();
		}
	}
	// This is my own custom listener so that the Activity and fragment can communicate.
	// If you are not familiar with this, google &quot;observer design pattern&quot;.
	public interface OnFragment1ClickedListener{
		public void onFragment1Clicked();
	}

}
</pre>
<p>This fragment has the click listener to call my custom listener&#8217;s abstract method onFragment1Clicked().</p>
<p>We now create another class Fragment2.java in which we do the exact same thing. However, this fragment will not call another fragment, so we do not have the interface and abstract method. Instead we just call a toast. Code:</p>
<pre class="brush: java; title: ; notranslate">
public class Fragment2 extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		super.onCreateView(inflater, container, savedInstanceState);

		View view = inflater.inflate(R.layout.fragment2, container, false);
		view.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Toast.makeText(getActivity(), &quot;THIS IS FRAGMENT2 BEING CLICKED!!! PRESS BACK TO GO TO FRAGMENT1&quot;, Toast.LENGTH_SHORT).show();
			}
		});
		return view;
	}

}
</pre>
<p>Now, we need three animations. I created one animation that fades away and another one that appears as the other fades and finally one that just appears so when users press the back button, they don&#8217;t have to wait for the fading animation; it doesn&#8217;t make sense. We need to create a folder inside the res folder &#8220;anim&#8221; and inside create three xml files: fragment_animation_fade_in.xml, fragment_animation_fade_out.xml, fragment_animation_no_fade_in.xml.<br />
Notice that with fragments we now have to use objectAnimator.</p>
<p>fragment_animation_fade_in.xml:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;objectAnimator xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:interpolator=&quot;@android:anim/linear_interpolator&quot;
    android:valueFrom=&quot;0&quot;
    android:valueTo=&quot;1&quot;
    android:propertyName=&quot;alpha&quot;
    android:duration=&quot;500&quot; /&gt;
</pre>
<p>fragment_animation_fade_out.xml:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;objectAnimator xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:interpolator=&quot;@android:anim/linear_interpolator&quot;
    android:valueFrom=&quot;1&quot;
    android:valueTo=&quot;0&quot;
    android:propertyName=&quot;alpha&quot;
    android:duration=&quot;500&quot; /&gt;
</pre>
<p>fragment_animation_no_fade_in.xml</p>
<pre class="brush: plain; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;objectAnimator xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:interpolator=&quot;@android:anim/linear_interpolator&quot;
    android:valueFrom=&quot;1&quot;
    android:valueTo=&quot;1&quot;
    android:propertyName=&quot;alpha&quot;
    android:duration=&quot;1&quot; /&gt;
</pre>
<p>So this was the easy part. Now we need to put everything together. We do this by creating an activity, Main.java, which will do all the work. Here is the code with comments and then I will explain further:</p>
<pre class="brush: java; title: ; notranslate">
public class Main extends Activity implements OnFragment1ClickedListener {
	// This is needed in order to manage the fragments.
	public Stack&lt;String&gt; mFragmentStack;

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

		mFragmentStack = new Stack&lt;String&gt;();

		// Dynamically add a fragment to an Activity
		FragmentManager fragmentManager = getFragmentManager();
		FragmentTransaction transaction = fragmentManager.beginTransaction();
		Fragment fragment = new Fragment1();
		String tag = fragment.toString();
		mFragmentStack.add(tag);
		transaction.add(R.id.fragment_swap, fragment,tag);
		transaction.addToBackStack(tag);
		transaction.commit();

	}

	// Notice how this class implements OnFragment1ClickkedListener? Well this causes us to
	// implement the abstract method onFragment1Clicked() from Fragment1.java.
	@Override
	public void onFragment1Clicked() {
		Fragment newFragment = new Fragment2();
		Bundle args = new Bundle();
		// by doing newFragment.toString(), I am taking a unique identified of that object.
		String tag = newFragment.toString();
		newFragment.setArguments(args);

		FragmentTransaction transaction = getFragmentManager().beginTransaction();
		// setting the animations here. the fade_in animation for fragment1 and fade_out for fragment2
		transaction.setCustomAnimations(R.anim.fragment_animation_fade_in, R.anim.fragment_animation_fade_out);
		// I find what the current fragment from the stack is, take it and hide it
		// using transaction.hide(currentFragment);
		Fragment currentFragment = getFragmentManager().findFragmentByTag(mFragmentStack.peek());
		transaction.hide(currentFragment);

		transaction.add(R.id.fragment_swap, newFragment,newFragment.toString());
		// This is important, we must addToBackStack so we can pull it out later.
		transaction.addToBackStack(tag);
		// Instead of using replace we use add. Why? If we use replace, then the previous
		// fragment will always have to be re-created. What if you don't want to do that. In
		// my case, I didn't want it to be re-created all the time because I had a position
		// set and by re-creating it, I would have lost the position or had to use static flag.
		mFragmentStack.add(tag);

		transaction.commit();
	}

	@Override
	public void onBackPressed(){
		// from the stack we can get the latest fragment
		Fragment fragment = getFragmentManager().findFragmentByTag(mFragmentStack.peek());
		// If its an instance of Fragment1 I don't want to finish my activity, so I launch a Toast instead.
		if (fragment instanceof Fragment1){
			Toast.makeText(getApplicationContext(), &quot;YOU ARE AT THE TOP FRAGMENT&quot;, Toast.LENGTH_SHORT).show();
		}
		else{
			// Remove the framg
			removeFragment();
			super.onBackPressed();
		}
	}
	private void removeFragment(){
		// remove the current fragment from the stack.
		mFragmentStack.pop();
		FragmentTransaction transaction = getFragmentManager().beginTransaction();
		// get fragment that is to be shown (in our case fragment1).
		Fragment fragment = getFragmentManager().findFragmentByTag(mFragmentStack.peek());
		// This time I set an animation with no fade in, so the user doesn't wait for the animation in back press
		transaction.setCustomAnimations(R.anim.fragment_animation_no_fade_in, R.anim.fragment_animation_fade_out);
		// We must use the show() method.
		transaction.show(fragment);
		transaction.commit();
	}

}
</pre>
<p>So basically I keep a stack of fragments that I am using so I can use as many fragments as I want. I am only using two right now, but this will work with 3 or more as well as long as the code in onFragment1Clicked() is used (slightly modified for other fragments of course). Also I am using the FragmentTransaction method hide() to hide my previous fragments and instead of replace() I am using add(). That is all, happy fragmenting?</p>
]]></content:encoded>
			<wfw:commentRss>http://adblogcat.com/fragment-transition-animations-while-hiding-the-previous-fragment/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Custom View to draw, rotate, erase and convert images to black and white.</title>
		<link>http://adblogcat.com/custom-view-to-draw-rotate-erase-and-convert-images-to-black-and-white/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=custom-view-to-draw-rotate-erase-and-convert-images-to-black-and-white</link>
		<comments>http://adblogcat.com/custom-view-to-draw-rotate-erase-and-convert-images-to-black-and-white/#comments</comments>
		<pubDate>Thu, 03 May 2012 18:09:43 +0000</pubDate>
		<dc:creator>guitarbaka</dc:creator>
				<category><![CDATA[Canvas]]></category>
		<category><![CDATA[UI]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[cavas]]></category>
		<category><![CDATA[draw]]></category>
		<category><![CDATA[drawable]]></category>
		<category><![CDATA[gesture]]></category>
		<category><![CDATA[image]]></category>
		<category><![CDATA[scale]]></category>

		<guid isPermaLink="false">http://adblogcat.com/?p=428</guid>
		<description><![CDATA[This article describes how to create a reusable class that can upload images from our Gallery or take a picture, put them on a canvas and move them around the screen, resize them, erase them and convert them to black &#8230; <a href="http://adblogcat.com/custom-view-to-draw-rotate-erase-and-convert-images-to-black-and-white/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="tall" count="1" href="http://adblogcat.com/custom-view-to-draw-rotate-erase-and-convert-images-to-black-and-white/"></g:plusone></div><p id="top" /><a href="http://adblogcat.com/wp-content/uploads/2012/05/canvasView.png"><img class="alignleft  wp-image-294" title="android_php_mysql" src="http://adblogcat.com/wp-content/uploads/2012/05/canvasView.png" alt="" width="98" height="180" /></a>This article describes how to create a reusable class that can upload images from our Gallery or take a picture, put them on a canvas and move them around the screen, resize them, erase them and convert them to black and white. This tutorial uses a class that extends View and uses onTouchEvents. This is class also takes care of the VM Budget issue of loading images from the gallery by optimizing the memory each image uses. It uses android 2.2 and above.</p>
<p><span id="more-428"></span></p>
<p>Before buying this article, you can download the apk file here: http://ece301-examples.googlecode.com/files/CanvasView.apk</p>
<p>This is a class I created as part of an application I am working on where I need users to select images and put them onto the screen, move them around and resize them. So lets get started.</p>
<p><script type="text/javascript"><!--
google_ad_client = "ca-pub-1316223412202970";
/* 300_250_medium_rectangle_custom */
google_ad_slot = "1912768919";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
<p>First, we create a project &#8220;CanvasView&#8221;. The package name is com.canvas.view.library. We create two classes; Stye.java and TouchView.java. Style.java will be the activity.</p>
<p>The main.xml will contain the following code:</p>
<pre class="brush: java; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
	android:orientation=&quot;vertical&quot; android:layout_width=&quot;fill_parent&quot;
	android:layout_height=&quot;fill_parent&quot; android:id=&quot;@+id/style_layout&quot;
	android:background=&quot;#2be5e7&quot;&gt;
	&lt;Button android:layout_width=&quot;wrap_content&quot;
		android:layout_height=&quot;wrap_content&quot; android:text=&quot;Picture&quot;
		android:id=&quot;@+id/camera_button&quot; android:layout_alignParentBottom=&quot;true&quot;&gt;&lt;/Button&gt;
	&lt;Button android:layout_width=&quot;wrap_content&quot;
		android:layout_height=&quot;wrap_content&quot; android:text=&quot;Image to BW&quot;
		android:id=&quot;@+id/bw_button&quot; android:layout_toRightOf=&quot;@id/camera_button&quot;
		android:layout_alignParentBottom=&quot;true&quot;&gt;&lt;/Button&gt;
	&lt;Button android:layout_width=&quot;wrap_content&quot;
		android:layout_height=&quot;wrap_content&quot; android:text=&quot;Trash&quot; android:id=&quot;@+id/trash_button&quot;
		android:layout_toRightOf=&quot;@id/bw_button&quot;
		android:layout_alignParentBottom=&quot;true&quot;&gt;&lt;/Button&gt;
&lt;/RelativeLayout&gt;
</pre>
<p>Now we will start modifying TouchView. TouchView will extend View, thus allowing us to create custom views that we can draw on and do different things. First, I will show the variables that will be used and the constructor.</p>
<pre class="brush: java; title: ; notranslate">
public class TouchView extends View {

	private static final int INVALID_POINTER_ID = -1;

	private final String TAG = &quot;TESTESTEST&quot;;

	private Drawable mImage;

	public void setmImage(Drawable image){
		mImage = image;
	}
	// width and height of original image
	private float mImageWidth;
	private float mImageHeight;

	// when image is scaled, we use this to calculate the bounds of the image
	private int mImageWidthScaled;
	private int mImageHeightScaled;

	public float mPosX = 150;
	public float mPosY = 300;

	public float getmPosX() {
		return mPosX;
	}

	public void setmPosX(float mPosX) {
		this.mPosX = mPosX;
	}

	public float getmPosY() {
		return mPosY;
	}

	public void setmPosY(float mPosY) {
		this.mPosY = mPosY;
	}

	private float mLastTouchX;
	private float mLastTouchY;

	private Paint mBorderLeftLine;
	private Paint mBorderTopLine;
	private Paint mBorderRightLine;
	private Paint mBorderBottomLine;

	private int mActivePointerId = INVALID_POINTER_ID;
	private ScaleGestureDetector mScaleDetector;
	private float mScaleFactor = 1f;

	// this is to tell Style what view number I am in the array.
	private int mNumberView;

	// this is what draws the red line around the TouchView to tell the user
	// this one is currently selected
	private boolean mSelected = false;

	public void setmSelected(boolean mSelected) {
		this.mSelected = mSelected;
	}

	private Style mStyle;

	// this is to keep a reference to the original image, so when we ship, we can tar
	// the images that are needed.
	private String mUri;

	public void setImageLocation(String path){
		this.mUri = path;
	}

	public TouchView(Context context,Style style, BitmapDrawable image, int count, float scaleFactor){
		super(context);
		this.mImage = image;
		mImageWidth = image.getBitmap().getWidth();
		mImageHeight = image.getBitmap().getHeight();
		mImageWidthScaled = (int) (mImageWidth*scaleFactor);
		mImageHeightScaled = (int) (mImageHeight*scaleFactor);
		this.mNumberView = count;
		this.mStyle = style;
		this.mScaleFactor = scaleFactor;
		init(context);
	}
</pre>
<p>Lets only focus on the constructor right now. The constructor passes a Drawable which will be the image for this view. The imageWidth and Height must be defined in the constructor. What these values will do is give me the actual image width and height used in the view. Later we will use these values for when we have different views and the user clicks on individual ones, that view consumes the onTouchView event. Intrinsic Width and height did not work well for me.</p>
<p>The mNumberView will define which View I am. In Style.java I will have an ArrayList with the list of views. This is how I manage the views.</p>
<p>mScaleFactor is the scale factor for zooming in and out the image.</p>
<p>Next piece of code initializes values for drawing to happen when onDraw() is called.</p>
<pre class="brush: java; title: ; notranslate">
private void init(Context context) {
		mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
		mBorderLeftLine = new Paint();
		mBorderRightLine = new Paint();
		mBorderBottomLine = new Paint();
		mBorderTopLine = new Paint();
		setBorderParams(Color.RED,2);

	}

	private void setBorderParams(int color, float width) {
		mBorderLeftLine.setColor(color);
		mBorderLeftLine.setStrokeWidth(width);
		mBorderRightLine.setColor(color);
		mBorderRightLine.setStrokeWidth(width);
		mBorderBottomLine.setColor(color);
		mBorderBottomLine.setStrokeWidth(width);
		mBorderTopLine.setColor(color);
		mBorderTopLine.setStrokeWidth(width);
		mImage.setBounds(0, 0,mImage.getIntrinsicWidth(),mImage.getIntrinsicHeight());

	}

	public void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		canvas.save();
		canvas.translate(mPosX, mPosY);
		canvas.scale(mScaleFactor, mScaleFactor);
		mImage.draw(canvas);
		if (mSelected){
			canvas.drawLine(0,
					0,
					mImage.getIntrinsicWidth(),
					0,
					mBorderTopLine);
			canvas.drawLine(0, mImage.getIntrinsicHeight(),
					mImage.getIntrinsicWidth(),
					mImage.getIntrinsicHeight(),
					mBorderBottomLine);
			canvas.drawLine(0,
					0,
					0,
					mImage.getIntrinsicHeight(),
					mBorderLeftLine);
			canvas.drawLine(mImage.getIntrinsicWidth(),
					0,
					mImage.getIntrinsicWidth(),
					mImage.getIntrinsicHeight(),
					mBorderRightLine);
		}
		canvas.restore();
	}
</pre>
<p>The constructor calls the method init(context); Because I am drawing a red rectangle around the image that is currently in use by a user, I create Paints for each line and setBorderParams(); sets the color and stroke width of those lines. ALSO, very important is mImage.setBounds(); If I do not do this, the image (Drawable) will not draw when onDraw() is called.</p>
<p>onDraw() method simply calls canvas.translate() to move the image around the screen by using mPosX and mPosY values. These values are set in my onTouchEvent and we will see how later.<br />
OnDraw() also uses canvas.scale() to scale the image depending when a user uses multitouch to stretch the image.<br />
OnDraw() also draws the a red rectangle around the currently selected image by a user. This is done with a boolean, mSelected.</p>
<p>I think so far, things are simple. But the difficult part of this class is the onTouchEvent method. onTouchEvent is used for the following:</p>
<p>1. Find out when the user does multitouch.<br />
2. Move the image around by setting the values mPosX and mPosY<br />
3. Check if this view is the one being selected because we can have more than 1 of these views on the screen at any time. (In the picture for this article I have 4. Each image represents an object of this view). </p>
<pre class="brush: java; title: ; notranslate">
public boolean onTouchEvent(MotionEvent event) {
		//ImageView view = (ImageView) v;
		mScaleDetector.onTouchEvent(event);
		boolean intercept = false;
		//boolean defaultResult = onTouchEvent(event);

		switch (event.getAction() &amp; MotionEvent.ACTION_MASK) {

		case MotionEvent.ACTION_DOWN:
			mLastTouchX = event.getX();
			mLastTouchY = event.getY();
			mActivePointerId = event.getPointerId(0);
			// this should mean that I accept the touch out of all my views
			/*if (((mLastTouchX &gt;= mPosX) &amp;&amp; (mLastTouchX &lt;= mPosX+ mImage.getIntrinsicWidth())
					&amp;&amp; (mLastTouchY &gt;= mPosY) &amp;&amp; (mLastTouchY &lt;= mPosY + mImage.getIntrinsicHeight())))*/
			if (((mLastTouchX &gt;= mPosX) &amp;&amp; (mLastTouchX &lt;= mPosX+ mImageWidthScaled)
					&amp;&amp; (mLastTouchY &gt;= mPosY) &amp;&amp; (mLastTouchY &lt;= mPosY + mImageHeightScaled))){
				Log.i(TAG,&quot;My view is here: &quot;+mNumberView);
				intercept = true;
				mSelected = true;
				mStyle.setmCurrentView(mNumberView);

			}

			Log.i(TAG,&quot;Action down&quot;);
			Log.i(TAG,&quot;x is: &quot;+mLastTouchX);
			Log.i(TAG,&quot;y is: &quot;+mLastTouchY);
			break;
		case MotionEvent.ACTION_UP:
			setFocusable(false);
			mImageWidthScaled = (int) (mImageWidth*mScaleFactor);
			mImageHeightScaled = (int) (mImageHeight*mScaleFactor);
			/*			mPosX = (int) event.getX();
			mPosY = (int) event.getY();*/
			mActivePointerId = INVALID_POINTER_ID;
			// stop the red rectangle from being drawn around the View
			mSelected = false;
			break;
		case MotionEvent.ACTION_CANCEL:
			mActivePointerId = INVALID_POINTER_ID;
			// stop the red rectangle from being drawn around the View
			mSelected = false;
			break;
		case MotionEvent.ACTION_MOVE:
			final int pointerIndex = event.findPointerIndex(mActivePointerId);
			final float x = event.getX(pointerIndex);
			final float y = event.getY(pointerIndex);
			if (!mScaleDetector.isInProgress()) {
				final float dx = x - mLastTouchX;
				final float dy = y - mLastTouchY;

				mPosX += dx;
				mPosY += dy;

				// Invalidate to request a redraw
				invalidate();
			}
			else{
				Log.i(TAG,&quot;Now scaling is happening&quot;);
			}
			// Remember this touch position for the next move event
			mLastTouchX = x;
			mLastTouchY = y;

			break;
		case MotionEvent.ACTION_POINTER_UP:
			final int pointerIndex2 = (event.getAction() &amp; MotionEvent.ACTION_POINTER_ID_MASK)
			&gt;&gt; MotionEvent.ACTION_POINTER_ID_SHIFT;
					final int pointerId = event.getPointerId(pointerIndex2);
					if (pointerId == mActivePointerId) {
						// This was our active pointer going up. Choose a new
						// active pointer and adjust accordingly.
						final int newPointerIndex = pointerIndex2 == 0 ? 1 : 0;
						mLastTouchX = event.getX(newPointerIndex);
						mLastTouchY = event.getY(newPointerIndex);
						mActivePointerId = event.getPointerId(newPointerIndex);
					}
					break;
					default:
						//return defaultResult;
		}
		return intercept;
	}
</pre>
<p>When first doing an ACION_DOWN I get the pixel values where the user is touching. The if statement is checking if these pixel values (x,y) are inside the image location. So my image is at position (100,200) with a width of 50 and height of 50, then it is checking if the touch falls within those bounds, if it does, then I set the boolean intercept to true, else to false. See that at the end we return intercept. This means that if onTouchEvent returns false, this view does not consume the touch and is passed to other views. Also mActivePointerId = event.getPointerId(0); is getting the pointerId for multitouch events. </p>
<p>Here is the code again for the case ACTION_DOWN:</p>
<pre class="brush: java; title: ; notranslate">
case MotionEvent.ACTION_DOWN:
			mLastTouchX = event.getX();
			mLastTouchY = event.getY();
			mActivePointerId = event.getPointerId(0);
			if (((mLastTouchX &gt;= mPosX) &amp;&amp; (mLastTouchX &lt;= mPosX+ mImageWidthScaled)
					&amp;&amp; (mLastTouchY &gt;= mPosY) &amp;&amp; (mLastTouchY &lt;= mPosY + mImageHeightScaled))){
				Log.i(TAG,&quot;My view is here: &quot;+mNumberView);
				intercept = true;
				mSelected = true;
				mStyle.setmCurrentView(mNumberView);

			}

			Log.i(TAG,&quot;Action down&quot;);
			Log.i(TAG,&quot;x is: &quot;+mLastTouchX);
			Log.i(TAG,&quot;y is: &quot;+mLastTouchY);
			break;
</pre>
<p>Now on ACTION_UP recalculates the width and height of the image in case it was stretched. It also makes the view unfocused. This is so that when we try to click on another object, the program doesn&#8217;t think we are still focused on this object and moves this one instead. Here it is again:</p>
<pre class="brush: java; title: ; notranslate">
case MotionEvent.ACTION_UP:
			setFocusable(false);
			mImageWidthScaled = (int) (mImageWidth*mScaleFactor);
			mImageHeightScaled = (int) (mImageHeight*mScaleFactor);
			/*			mPosX = (int) event.getX();
			mPosY = (int) event.getY();*/
			mActivePointerId = INVALID_POINTER_ID;
			// stop the red rectangle from being drawn around the View
			mSelected = false;
			break;
</pre>
<p>ACTION_CANCEL doesn&#8217;t really do anything so I won&#8217;t go over it.</p>
<p>ACTION_MOVE check that currently the view is not being scaled (stretched) and if it is not, then it moves the image around the screen.</p>
<pre class="brush: java; title: ; notranslate">
case MotionEvent.ACTION_MOVE:
			final int pointerIndex = event.findPointerIndex(mActivePointerId);
			final float x = event.getX(pointerIndex);
			final float y = event.getY(pointerIndex);
			if (!mScaleDetector.isInProgress()) {
				final float dx = x - mLastTouchX;
				final float dy = y - mLastTouchY;

				mPosX += dx;
				mPosY += dy;

				// Invalidate to request a redraw
				invalidate();
			}
			else{
				Log.i(TAG,&quot;Now scaling is happening&quot;);
			}
			// Remember this touch position for the next move event
			mLastTouchX = x;
			mLastTouchY = y;

			break;
</pre>
<p>Finally POINTER_UP is used for multitouch events and mainly here for stretching the image when a user uses multitouch.</p>
<pre class="brush: java; title: ; notranslate">
case MotionEvent.ACTION_POINTER_UP:
			final int pointerIndex2 = (event.getAction() &amp; MotionEvent.ACTION_POINTER_ID_MASK)
			&gt;&gt; MotionEvent.ACTION_POINTER_ID_SHIFT;
					final int pointerId = event.getPointerId(pointerIndex2);
					if (pointerId == mActivePointerId) {
						// This was our active pointer going up. Choose a new
						// active pointer and adjust accordingly.
						final int newPointerIndex = pointerIndex2 == 0 ? 1 : 0;
						mLastTouchX = event.getX(newPointerIndex);
						mLastTouchY = event.getY(newPointerIndex);
						mActivePointerId = event.getPointerId(newPointerIndex);
					}
					break;
</pre>
<p>Now in order to do multitouch and be able to scale the image, we have to create a class inside this class. It extends ScaleGestureDetector and this is the reason why we need to use android 2.2. </p>
<pre class="brush: java; title: ; notranslate">
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
		@Override
		public boolean onScale(ScaleGestureDetector detector) {
			mScaleFactor *= detector.getScaleFactor();

			// Don't let the object get too small or too large.
			mScaleFactor = Math.max(0.05f, Math.min(mScaleFactor, 2.0f));
			invalidate();
			Log.i(TAG,&quot;New Image size: widht: &quot;+mImage.getIntrinsicWidth()+&quot; height: &quot;+mImage.getIntrinsicHeight());
			return true;
		}
	}
</pre>
<p>All it does it when we detect that scaling is happening, it calculates the scale factor. in the onDraw method we have canvas.scale(). This is where this value comes in and scales the image accordingly. </p>
<p>Finally as an added bonus, I do some image processing to turn the image from color to black and white</p>
<pre class="brush: java; title: ; notranslate">
public void greyScaler() {
		ColorMatrix cm = new ColorMatrix();
		cm.set(new float[] {
				.21f, .71f, .07f, 0, 0,
				.21f, .71f, .07f, 0, 0,
				.21f, .71f, .07f, 0, 0,
				0, 0, 0, 1, 0 });
		mImage.setColorFilter(new ColorMatrixColorFilter(cm));
		invalidate();
	}
</pre>
<p>It took me a while to figure it out since I never worked with ColorMatrix before. The array you see is a multiplier. It comes from here: http://developer.android.com/reference/android/graphics/ColorMatrix.html</p>
<p>Basically the RGB colors + Alpha are multiplied by the matrix values above. One algorithm for black and white is to as follows .21*R + .71*G + .07B. This is what I have above. invalidate is called every time we want the onDraw() method to be called manually by us. In my case, after changing the image filter, it will not update until onDraw is called, thus I call it.</p>
<p>If you are following me so far, we are not done yet.We have created the Object that will take care of all the work for us to move the image, scale it, etc. This class can be extended and other methods added or you can add other methods yourself that you might need. Like some extra image processing, rotation, etc.</p>
<p>Style.java extends Activity and holds an ArrayList of type TouchView to keep track of our object creation. Let&#8217;s start with the variables and onCreate method:</p>
<pre class="brush: java; title: ; notranslate">
public class Style extends Activity {

	private final static String TAG = &quot;TESTESTESTEST&quot;;

	// to take a picture
	private static final int CAMERA_PIC_REQUEST = 1111;
	private static final int GALLERY_PIC_REQUEST = 1112;

	private Button mCameraButton;
	private Button mBwButton;
	private Button mTrashButton;

	// current view is the current selected view - hopefully this will work ok
	private int mCurrentView = 0;

	public int getmCurrentView() {
		return mCurrentView;
	}

	public void setmCurrentView(int mCurrentView) {
		this.mCurrentView = mCurrentView;
	}

	// this tells me how many views I currently have.
	private int mViewsCount = 0;

	private ArrayList&lt;View&gt; mViewsArray = new ArrayList&lt;View&gt;();

	private static Style mStyle;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.main);

		mStyle = this;

		mTrashButton = (Button) findViewById(R.id.trash_button);
		mTrashButton.setClickable(true);
		mTrashButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Log.i(TAG,&quot;Trash clicked&quot;);
				Log.i(TAG,&quot;Array size is: &quot;+mViewsArray.size());
				if (mViewsArray.size() &gt; 0){
					Log.i(TAG,&quot;Should remove this view&quot;);
					RelativeLayout layout = (RelativeLayout) findViewById(R.id.style_layout);
					layout.removeView(mViewsArray.get(mCurrentView));
					mViewsArray.remove(mCurrentView);
					mViewsCount -=1;
				}

			}
		});

		mCameraButton = (Button) findViewById(R.id.camera_button);
		mCameraButton.setClickable(true);
		mCameraButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
				builder.setTitle(&quot;Select:&quot;);
				final CharSequence[] chars = {&quot;Take Picture&quot;, &quot;Choose from Gallery&quot;};
				builder.setItems(chars, new android.content.DialogInterface.OnClickListener(){

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if(which == 0){
							Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
							startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
						}else
							if(which == 1){
								Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
								startActivityForResult(intent,GALLERY_PIC_REQUEST);
							}
						dialog.dismiss();
					}

				}
				);
				builder.show();
			}
		});

		mBwButton = (Button) findViewById(R.id.bw_button);
		mBwButton.setClickable(true);
		mBwButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mViewsArray.size() &gt; 0){
					((TouchView) mViewsArray.get(mCurrentView)).greyScaler();
				}
				else{
					Toast.makeText(v.getContext(), &quot;Please select an image first before using this function.&quot;, Toast.LENGTH_SHORT).show();
				}
			}
		});
	}
</pre>
<p>The onCreate method holds my click listeners for my buttons to erase, take photo and make black and white.</p>
<p>The trash button removes the view from both the layout and then ArrayList, mViewsArray. Here it is again:</p>
<pre class="brush: java; title: ; notranslate">
mTrashButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Log.i(TAG,&quot;Trash clicked&quot;);
				Log.i(TAG,&quot;Array size is: &quot;+mViewsArray.size());
				if (mViewsArray.size() &gt; 0){
					Log.i(TAG,&quot;Should remove this view&quot;);
					RelativeLayout layout = (RelativeLayout) findViewById(R.id.style_layout);
					layout.removeView(mViewsArray.get(mCurrentView));
					mViewsArray.remove(mCurrentView);
					mViewsCount -=1;
				}

			}
		});
</pre>
<p>mViewsCount keeps a count of TouchViews created. </p>
<p>mCameraButton creates an Alert to let a user choose between using a current image from the Gallery or take a picture. Here it is again:</p>
<pre class="brush: java; title: ; notranslate">
mCameraButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
				builder.setTitle(&quot;Select:&quot;);
				final CharSequence[] chars = {&quot;Take Picture&quot;, &quot;Choose from Gallery&quot;};
				builder.setItems(chars, new android.content.DialogInterface.OnClickListener(){

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if(which == 0){
							Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
							startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
						}else
							if(which == 1){
								Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
								startActivityForResult(intent,GALLERY_PIC_REQUEST);
							}
						dialog.dismiss();
					}

				}
				);
				builder.show();
			}
		});
</pre>
<p>It also uses android actions: android.provider.MediaStore.ACTION_IMAGE_CAPTURE and Intent.ACTION_PICK with android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI.</p>
<p>mBwButton calls the greyScaler() method in the TouchView to make the image black and white.</p>
<p>When creating these classes, I thought it would be useful to not only load the images from the gallery or from taking a picture, but also to keep track of its path. However, when we call startActivityForResult(). We do not get the absolute path, we I needed to add this function so I could get it.</p>
<p>[soucecode language="java"]<br />
	public String getPath(Uri uri){<br />
		String[] filePathColumn={MediaStore.Images.Media.DATA};</p>
<p>		Cursor cursor=getContentResolver().query(uri, filePathColumn, null, null, null);<br />
		cursor.moveToFirst();<br />
		int columnIndex=cursor.getColumnIndex(filePathColumn[0]);<br />
		Log.i(TAG,&#8221;Image path is: &#8220;+cursor.getString(columnIndex));<br />
		return cursor.getString(columnIndex);<br />
	}<br />
[/sourcecode]</p>
<p>Finally, the last thing we need to do here is onActivityResult();</p>
<pre class="brush: java; title: ; notranslate">
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// usedView is a bool that checks is a view was destroyed and this was reused.
		// if it wasn't reused, this means we create a new one.
		if (requestCode == CAMERA_PIC_REQUEST) {
			try{
				Uri selectedImage = data.getData();
				getPath(selectedImage);
				InputStream is;
				is = getContentResolver().openInputStream(selectedImage);
				BitmapFactory.Options opts = new BitmapFactory.Options();
				opts.inJustDecodeBounds = true;
				//BitmapFactory.decodeStream(bis,null,opts);
				BitmapFactory.decodeStream(is,null,opts);

				//The new size we want to scale to
				final int REQUIRED_SIZE=200;

				//Find the correct scale value. It should be the power of 2.
				int scale=1;
				while(opts.outWidth/scale/2&gt;=REQUIRED_SIZE || opts.outHeight/scale/2&gt;=REQUIRED_SIZE)
					scale*=2;

				Log.i(TAG,&quot;Scale is: &quot;+scale);
				opts.inSampleSize = scale;
				opts.inJustDecodeBounds = false;
				is = null;
				System.gc();
				InputStream is2 = getContentResolver().openInputStream(selectedImage);

				Bitmap returnedImage = BitmapFactory.decodeStream(is2, null, opts);
				Log.i(TAG,&quot;Image width from bitmap: &quot;+returnedImage.getWidth());
				Log.i(TAG,&quot;Image height from bitmap: &quot;+returnedImage.getHeight());
				Log.i(TAG,&quot;Creating another View&quot;);
				TouchView newView = new TouchView(this,mStyle,new BitmapDrawable(returnedImage),mViewsCount,1f);
				newView.setImageLocation(getPath(selectedImage));
				newView.setClickable(true);
				// below is to ensure red border is drawn on new selected image
				newView.setmSelected(true);
				mViewsArray.add(newView);
				RelativeLayout layout = (RelativeLayout) findViewById(R.id.style_layout);
				layout.addView(mViewsArray.get(mViewsCount));
				newView.invalidate();
				mViewsCount+=1;
			}
			catch(NullPointerException e){
				//Do nothing
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (requestCode == GALLERY_PIC_REQUEST){
			try {
				Uri selectedImage = data.getData();
				getPath(selectedImage);
				InputStream is;
				is = getContentResolver().openInputStream(selectedImage);
				BitmapFactory.Options opts = new BitmapFactory.Options();
				opts.inJustDecodeBounds = true;
				//BitmapFactory.decodeStream(bis,null,opts);
				BitmapFactory.decodeStream(is,null,opts);

				//The new size we want to scale to
				final int REQUIRED_SIZE=200;

				//Find the correct scale value. It should be the power of 2.
				int scale=1;
				while(opts.outWidth/scale/2&gt;=REQUIRED_SIZE || opts.outHeight/scale/2&gt;=REQUIRED_SIZE)
					scale*=2;

				Log.i(TAG,&quot;Scale is: &quot;+scale);
				opts.inSampleSize = scale;
				opts.inJustDecodeBounds = false;
				is = null;
				System.gc();
				InputStream is2 = getContentResolver().openInputStream(selectedImage);

				Bitmap returnedImage = BitmapFactory.decodeStream(is2, null, opts);
				Log.i(TAG,&quot;Image width from bitmap: &quot;+returnedImage.getWidth());
				Log.i(TAG,&quot;Image height from bitmap: &quot;+returnedImage.getHeight());
				Log.i(TAG,&quot;Creating another View&quot;);
				TouchView newView = new TouchView(this,mStyle,new BitmapDrawable(returnedImage),mViewsCount,1f);
				newView.setImageLocation(getPath(selectedImage));
				newView.setClickable(true);
				// below is to ensure red border is drawn on new selected image
				newView.setmSelected(true);
				mViewsArray.add(newView);
				RelativeLayout layout = (RelativeLayout) findViewById(R.id.style_layout);
				layout.addView(mViewsArray.get(mViewsCount));
				newView.invalidate();
				mViewsCount+=1;
			} catch (FileNotFoundException e) {

			}
			catch (NullPointerException e){
			}
		}
	}
</pre>
<p>Now, this method is longer than it needs to be. Both GALLERY request and PIC REQUEST use the same algorithm. However, I decided to separate them just in case one of them needed something different than the other. Or if I wanted to change the size from grabbing images from Gallery vs taking the picture.</p>
<p>The algorithm is this:</p>
<pre class="brush: java; title: ; notranslate">
Uri selectedImage = data.getData();
				getPath(selectedImage);
				InputStream is;
				is = getContentResolver().openInputStream(selectedImage);
				BitmapFactory.Options opts = new BitmapFactory.Options();
				opts.inJustDecodeBounds = true;
				//BitmapFactory.decodeStream(bis,null,opts);
				BitmapFactory.decodeStream(is,null,opts);

				//The new size we want to scale to
				final int REQUIRED_SIZE=200;

				//Find the correct scale value. It should be the power of 2.
				int scale=1;
				while(opts.outWidth/scale/2&gt;=REQUIRED_SIZE || opts.outHeight/scale/2&gt;=REQUIRED_SIZE)
					scale*=2;

				Log.i(TAG,&quot;Scale is: &quot;+scale);
				opts.inSampleSize = scale;
				opts.inJustDecodeBounds = false;
				is = null;
				System.gc();
				InputStream is2 = getContentResolver().openInputStream(selectedImage);

				Bitmap returnedImage = BitmapFactory.decodeStream(is2, null, opts);
				Log.i(TAG,&quot;Image width from bitmap: &quot;+returnedImage.getWidth());
				Log.i(TAG,&quot;Image height from bitmap: &quot;+returnedImage.getHeight());
				Log.i(TAG,&quot;Creating another View&quot;);
				TouchView newView = new TouchView(this,mStyle,new BitmapDrawable(returnedImage),mViewsCount,1f);
				newView.setImageLocation(getPath(selectedImage));
				newView.setClickable(true);
				// below is to ensure red border is drawn on new selected image
				newView.setmSelected(true);
				mViewsArray.add(newView);
				RelativeLayout layout = (RelativeLayout) findViewById(R.id.style_layout);
				layout.addView(mViewsArray.get(mViewsCount));
				newView.invalidate();
				mViewsCount+=1;
</pre>
<p>First I get the Uri of the image.I quickly found that I was running out of memory after loading only 3 images because I was loading the images to memory and it was exceeding my VM Budget (they were 8 megapixel images). Following this: http://developer.android.com/training/displaying-bitmaps/load-bitmap.html</p>
<p>I created a scaled version of my images which greatly reduced the memory usage. You can read about it, but the main part for this was: </p>
<pre class="brush: java; title: ; notranslate">
BitmapFactory.Options opts = new BitmapFactory.Options();
				opts.inJustDecodeBounds = true;
				//BitmapFactory.decodeStream(bis,null,opts);
				BitmapFactory.decodeStream(is,null,opts);

				//The new size we want to scale to
				final int REQUIRED_SIZE=200;

				//Find the correct scale value. It should be the power of 2.
				int scale=1;
				while(opts.outWidth/scale/2&gt;=REQUIRED_SIZE || opts.outHeight/scale/2&gt;=REQUIRED_SIZE)
					scale*=2;

				Log.i(TAG,&quot;Scale is: &quot;+scale);
				opts.inSampleSize = scale;
				opts.inJustDecodeBounds = false;
				is = null;
				System.gc();
				InputStream is2 = getContentResolver().openInputStream(selectedImage);

				Bitmap returnedImage = BitmapFactory.decodeStream(is2, null, opts);
</pre>
<p>I won&#8217;t go over the details as you can read about it on the link above, but this was a great optimization to my code.</p>
<p>Finally, Once I have the bitmap I use BitmapDrawable to pass a Drawable from a Bitmap to the constructor of TouchView along with other values. I then call my RelativeLayout and add the view to relative layout (vs in the mTrashButton removes the view from my relative layout). This all happens here:</p>
<pre class="brush: java; title: ; notranslate">
Bitmap returnedImage = BitmapFactory.decodeStream(is2, null, opts);
				Log.i(TAG,&quot;Image width from bitmap: &quot;+returnedImage.getWidth());
				Log.i(TAG,&quot;Image height from bitmap: &quot;+returnedImage.getHeight());
				Log.i(TAG,&quot;Creating another View&quot;);
				TouchView newView = new TouchView(this,mStyle,new BitmapDrawable(returnedImage),mViewsCount,1f);
				newView.setImageLocation(getPath(selectedImage));
				newView.setClickable(true);
				// below is to ensure red border is drawn on new selected image
				newView.setmSelected(true);
				mViewsArray.add(newView);
				RelativeLayout layout = (RelativeLayout) findViewById(R.id.style_layout);
				layout.addView(mViewsArray.get(mViewsCount));
				newView.invalidate();
				mViewsCount+=1;
</pre>
<p>And that is it! You now have a basic library to use in your applications. Should save you a lot of time.</p>
]]></content:encoded>
			<wfw:commentRss>http://adblogcat.com/custom-view-to-draw-rotate-erase-and-convert-images-to-black-and-white/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Connect to MYSQL remote server database using PHP and display ListView</title>
		<link>http://adblogcat.com/connect-mysql-remote-server-php/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=connect-mysql-remote-server-php</link>
		<comments>http://adblogcat.com/connect-mysql-remote-server-php/#comments</comments>
		<pubDate>Tue, 21 Feb 2012 23:54:00 +0000</pubDate>
		<dc:creator>guitarbaka</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[HTTP]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[MYSQL]]></category>
		<category><![CDATA[Network]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[connect]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[remote]]></category>
		<category><![CDATA[server]]></category>

		<guid isPermaLink="false">http://adblogcat.com/?p=269</guid>
		<description><![CDATA[This article describes how to create/access a MYSQL database in a remote server from Android using PHP and display it on a ListView. Because most online tutorials did not show the full process or all source code, I decided how &#8230; <a href="http://adblogcat.com/connect-mysql-remote-server-php/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="tall" count="1" href="http://adblogcat.com/connect-mysql-remote-server-php/"></g:plusone></div><p id="top" /><a href="http://adblogcat.com/wp-content/uploads/2012/02/android_php_mysql.jpg"><img class="alignleft  wp-image-294" title="android_php_mysql" src="http://adblogcat.com/wp-content/uploads/2012/02/android_php_mysql-164x300.jpg" alt="" width="98" height="180" /></a>This article describes how to create/access a MYSQL database in a remote server from Android using PHP and display it on a ListView. Because most online tutorials did not show the full process or all source code, I decided how to create a fully functional prototype. Currently you can see my JSON objects by going to this link: <a href="http://www.ece301.com/food.php" target="_blank">http://www.ece301.com/food.php</a> which accesses my database and extracts the information. This article uses Cpanel, php and Android API 2.1.<br />
<span id="more-269"></span></p>
<p>This can easily run in XAMPP, but because most online tutorials focus on running it this way, I will show how to run it in a real live server.</p>
<p>Download the APK file first and install in your phone (adb install) before you think about buying this article. Look at the php JSON request here: <a href="http://www.ece301.com/food.php" target="_blank">http://www.ece301.com/food.php</a>:</p>
<h3><a href="http://ece301-examples.googlecode.com/files/JSONinAndroid.apk" target="_blank">DOWNLOAD APK FILE HERE</a></h3>
<p>                <p class="cleeng-prompt">
            <span class="cleeng-firsttime">
                This article is exclusive, use Cleeng to view it in full.            </span>
            <span class="cleeng-nofirsttime" style="display:none">
                The rest of this article is exclusive, use Cleeng again to view it.            </span>
            <span class="cleeng-auth" style="display:none">
                The rest of this article is exclusive,                <span class="cleeng-username"></span>,
                click "buy" and view it instantly.            </span>
        </p>
        
        <div id="cleeng-layer-606988255" class="cleeng-layer" >
        <div class="cleeng-protected-content" id="cleeng-606988255" rel="269" >Exclusive content</div>
        <div class="cleeng-layer-left"></div>

        <div class="cleeng-text">
                        <div class="cleeng-noauth-bar">
                <span class="cleeng-welcome-firsttime">
                    Already have a Cleeng account?                </span>

                <span class="cleeng-welcome-nofirsttime" style="display:none">
                Welcome back!                </span>
                <a class="cleeng-hlink cleeng-login" href="javascript:">Log-in</a>
            </div>
            <div class="cleeng-auth-bar" style="display:none">
                <a class="cleeng-hlink cleeng-logout" href="#">Logout</a>
                Welcome, <a class="cleeng-username" href="http://cleeng.com/my-account"></a>            </div>

                        <div class="cleeng-publisher">
                <div class="cleeng-ajax-loader">&nbsp;</div>
                <img src="http://cleeng.com/media/users/942/770/747_mini.png"
                     alt=""
                     title="" />
            </div>


            <h2 class="cleeng-description">All articles you purchase here have a money back guarantee if you are not completely satisfied.</h2>
            <div class="cleeng-rating">
                <span>Customer rating:</span>
                <div class="cleeng-stars cleeng-stars-4"></div>
            </div>

            <span class="cleeng-free-content-views" style="display:none">
                Good news! You still have <span></span> free purchase(s).            </span>
        </div>
        <div class="cleeng-text-bottom">
            <div class="cleeng-textBottom">
                <div class="cleeng-purchaseInfo-grad">
                </div>
                <div class="cleeng-purchaseInfo">
                    <div class="cleeng-purchaseInfo-text">

                        
                                
                                <div class="cleeng-button cleeng-middle  register-and-read-for-free-606988255 by-free-606988255">
                                    Register and read for free                                 </div>

                                <div class="cleeng-button cleeng-middle  register-and-watch-for-free-606988255 by-free-606988255">
                                    Register and watch for free                                 </div>

                                <div class="cleeng-button cleeng-middle  register-and-access-for-free-606988255 by-free-606988255">
                                    Register and access for free                                 </div>

                                <div class="cleeng-button cleeng-middle  read-for-free-606988255 by-free-606988255">
                                    Read for free                                 </div>

                                <div class="cleeng-button cleeng-middle  watch-for-free-606988255 by-free-606988255">
                                    Watch for free                                 </div>

                                <div class="cleeng-button cleeng-middle  access-for-free-606988255 by-free-606988255">
                                    Access for free                                 </div>

                                <div class="cleeng-button cleeng-middle  buy-this-article-606988255">
                                    Buy this article                                     <span class="cleeng-price">$0.99</span>
                                </div>

                                <div class="cleeng-button cleeng-middle  buy-this-video-606988255">
                                    Buy this video                                     <span class="cleeng-price">$0.99</span>
                                </div>

                                <div  class="cleeng-button cleeng-middle   buy-this-item-606988255">
                                    Buy this item                                     <span class="cleeng-price">$0.99</span>
                                </div>

                                <div id="cleeng-subscribe-606988255" class="cleeng-subscribe cleeng-button"
                                     style="display:none">                                </div>

                                                                    <style>
                                        .read-for-free-606988255, .watch-for-free-606988255, .access-for-free-606988255, .register-and-read-for-free-606988255, .register-and-watch-for-free-606988255, .register-and-access-for-free-606988255, .buy-this-article-606988255, .buy-this-video-606988255, .buy-this-item-606988255{display:none}                                        .buy-this-article-606988255 {
                                            display:block;
                                        }
                                    </style>

                        
                    </div>
                </div>
                <div class="cleeng-whatsCleeng" style="width:171px">
                     <div style="cursor:pointer;width:155px;line-height:12px;background: url('http://cleeng.com/logo/cleeng-small-500.png?contentId=606988255') no-repeat right top" href="http://cleeng.com/what-is-cleeng">Powered by</div>    
                     
                </div>
            </div>
        </div>

        <div class="cleeng-layer-right"></div>
    </div>
    <div id="cleeng-nolayer-606988255" class="cleeng-nolayer" style="display:none">
                <div class="cleeng-nolayer-top">
                    <a href="http://cleeng.com">
                        <img src="http://adblogcat.com/wp-content/plugins/cleeng/img/cleeng-small.png" alt="Cleeng: Instant access to quality content" />
                    </a>
                    <div class="cleeng-auth-bar">
                        <a class="cleeng-hlink cleeng-logout" href="#">
                            Logout                        </a>
                        Welcome, <a class="cleeng-username" href="http://cleeng.com/my-account"></a>                    </div>
                </div>

                <div class="cleeng-content">
                 </div>

             <div class="cleeng-nolayer-bottom">

                <span  class="cleeng-rate" style="display:none">
                    Rate:                    <a href="#" class="cleeng-icon cleeng-vote-liked">&nbsp;</a>
                    <a href="#" class="cleeng-icon cleeng-vote-didnt-like">&nbsp;</a>
                </span>
                <span style="float:left" class="cleeng-rating">
                    <!--Customer rating:-->
                    <span class="cleeng-stars cleeng-stars-4"></span>
                </span>
                <span class="cleeng-share">
                    <!--Share:-->
                    <a class="cleeng-icon cleeng-facebook" href="#">&nbsp;</a>
                    <a class="cleeng-icon cleeng-twitter" href="#">&nbsp;</a>
                    <a class="cleeng-icon cleeng-email" href="mailto:?subject=&amp;body=">&nbsp;</a>
                    <!--<span class="cleeng-referral-url-label">URL:</span>-->
                    <span class="cleeng-referral-url"></span>
                    <span class="cleeng-icon cleeng-copy">&nbsp;</span>
                </span>
                <span class="cleeng-referral-rate">
                    Earn: <span>5%</span> commission                </span>
              </div>
          </div>

    </p>
]]></content:encoded>
			<wfw:commentRss>http://adblogcat.com/connect-mysql-remote-server-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Android SAX XML Parsing</title>
		<link>http://adblogcat.com/android-sax-xml-parsing/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=android-sax-xml-parsing</link>
		<comments>http://adblogcat.com/android-sax-xml-parsing/#comments</comments>
		<pubDate>Fri, 17 Feb 2012 19:22:05 +0000</pubDate>
		<dc:creator>guitarbaka</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[XML]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[article]]></category>
		<category><![CDATA[example]]></category>
		<category><![CDATA[parsing]]></category>
		<category><![CDATA[sax]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://adblogcat.com/?p=263</guid>
		<description><![CDATA[This article describes how to create an XML Parser for Android. The files are located in the SD card and use a SAX parser. Why use XML? If you are designing an application that has static data, it might be &#8230; <a href="http://adblogcat.com/android-sax-xml-parsing/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="tall" count="1" href="http://adblogcat.com/android-sax-xml-parsing/"></g:plusone></div><p id="top" />This article describes how to create an XML Parser for Android. The files are located in the SD card and use a SAX parser. Why use XML? If you are designing an application that has static data, it might be simpler to keep information in a flat file instead of creating a database and query for values.<br />
<span id="more-263"></span></p>
<p>Here is the sample XML file that we will parse:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;AndroidGames&gt;
	&lt;GAMES&gt;
		&lt;Name&gt;Super Mario Brothers&lt;/Name&gt;
		&lt;LocationImage&gt;/sdcard/games/supermario.png&lt;/LocationImage&gt;
		&lt;Description&gt;Mario must save the princess from Browser&lt;/Description&gt;
	&lt;/GAMES&gt;
	&lt;GAMES&gt;
		&lt;Name&gt;Call of Duty&lt;/Name&gt;
		&lt;LocationImage&gt;/sdcard/games/callofduty.png&lt;/LocationImage&gt;
		&lt;Description&gt;Play online against your friends&lt;/Description&gt;
	&lt;/GAMES&gt;
	&lt;GAMES&gt;
		&lt;Name&gt;Aliens vs Predator&lt;/Name&gt;
		&lt;LocationImage&gt;/sdcard/games/aliensvspredator.png&lt;/LocationImage&gt;
		&lt;Description&gt;They win, we lose&lt;/Description&gt;
	&lt;/GAMES&gt;
	&lt;GAMES&gt;
		&lt;Name&gt;The land of happiness&lt;/Name&gt;
		&lt;LocationImage&gt;/sdcard/games/landofhappiness.png&lt;/LocationImage&gt;
		&lt;Description&gt;Something gay&lt;/Description&gt;
	&lt;/GAMES&gt;
&lt;/AndroidGames&gt;
</pre>
<p>In here I am making some app that has game information and an image location from the sd card.</p>
<h1>Create ContentObject.java</h1>
<p>This class contains the elements from the XML file you created. It looks something like this:</p>
<pre class="brush: java; title: ; notranslate">
public class ContentObject {
	private String mName;
	private String imageLocation;
	private String mDescription;

	/**
	 * Set functions
	 */
	public void setName (String name){
		mName = name;
	}
	public void setLocationImage(String location){
		imageLocation = location;
	}
	public void setDescription(String description){
		mDescription = description;
	}
	/**
	 * Get functions
	 */
	public String getName(){
		return mName;
	}
	public String getLocationImage(){
		return imageLocation;
	}
	public String getDescription(){
		return mDescription;
	}
}
</pre>
<p>If you notice the methods all they do is set and get:<br />
1. Name<br />
2. LocationImage<br />
3. Description</p>
<p>It is just like the XML file I created.</p>
<p>The setter methods will set the objects when the XML SAX parser is called. We will use the getter methods to get the information later so it can be used in our app.</p>
<h1>Create XmlSaxParser.java</h1>
<p>Now we create the XML parser:</p>
<pre class="brush: java; title: ; notranslate">
public class XmlSAXParser extends DefaultHandler{
	private String TAG = &quot;JUAN&quot;;
	private String mLocation;
	private String mSelection;
	public List&lt;ContentObject&gt; myContentObjects = new ArrayList&lt;ContentObject&gt;();
	private String tempVal;

	private ContentObject tempContentObject;

	/**constructor that sets the file Location (mLocation) and mSelection(GAMES in this case)*/
	public XmlSAXParser(String location, String selection){
		mLocation = location;
		mSelection = selection;
	}

	/**the heart of the parser. Initializes a SAXParserFactory and
	 *  uses the java classes to parse my file*/
	public void runParser(){
		try{
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			XMLReader xr = sp.getXMLReader();
			File file = new File(mLocation);
			FileInputStream fis = new FileInputStream(file);
			xr.setContentHandler(this);
			xr.parse(new InputSource(fis));
		} catch (Exception e) {
			Log.i(TAG,&quot;XML Pasing Excpetion = &quot; + e);
			System.exit(-1);
		}
	}

	/**These classes below are my event handlers
	 * When the xr.parse above takes effect, the startElement and endElement
	 * will grab the data and put it in my created class ContentObject*/

	/**when the start Element is found to be &quot;GAMES&quot;, I will create a new content object to hold
	 * my elements inside*/
	public void startElement
	(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		if (localName.equals(null)){
			Log.i(TAG,&quot;qName is empty&quot;);
		}
		tempVal = &quot;&quot;;
		if(localName.equalsIgnoreCase(mSelection)) {
			/**create a new ContentObject to hold all XML elements*/
			tempContentObject = new ContentObject();
		}
	}

	public void characters(char[] ch, int start, int length) throws SAXException {
		tempVal = new String(ch,start,length);
	}
	/**Once the end tag is found in XML, I write the element's data to the content object
	 * If &quot;GAMES&quot; ending tag is found, then I add to the List of my content objects*/
	public void endElement(String uri, String localName, String qName) throws SAXException {
		/**add the content object with the elements inside to my List of Content objects*/
		if(localName.equalsIgnoreCase(mSelection)) {
			myContentObjects.add(tempContentObject);
		}else if (localName.equalsIgnoreCase(&quot;Name&quot;)) {
			tempContentObject.setName(tempVal);
		}else if (localName.equalsIgnoreCase(&quot;LocationImage&quot;)) {
			tempContentObject.setLocationImage(tempVal);
		}
		else if (localName.equalsIgnoreCase(&quot;Description&quot;)){
			tempContentObject.setDescription(tempVal);
		}
	}

	/**I return a List of ContentObjects to be ready to be itterated*/
	public List&lt;ContentObject&gt; getParsedData(){
		return this.myContentObjects;
	}
}
</pre>
<p>Here we call a factory that returns a SAXParser instance, wrap our string as a file that is put into our parser and we parse (xr.parse()).</p>
<p>The methods startElement and endElement are called when in our XLM file an element tag is called. This parser here works with Element tags. If you add attributes, the code will have to be slightly modified. If you don&#8217;t know the difference between elements and attributes, just write everything like elements ( like I did above in my XML file) if its a simple XML file.<br />
When the mSelection START TAG is found, I create a ContentObject object. This is then used to SET the name, locationimage and<br />
description. the mSelection tag is &#8220;GAMES&#8221; because that is what my main tag to distinguish elements in my XML and you will see pretty<br />
soon. When mSelection ENDING TAG is found, then I add that ContentObject object to a list of ContentObjects. So for this XML file, I will<br />
have a List of 4 ContentObjects which contain all the information I collected.</p>
<p><b>NOTE: Why SAX? DOM keeps the whole file in memory. For an android device (embedded system) (your phone!) you don&#8217;t want to do that, so I choose SAX which is object modelled.</b></p>
<h1>Create TestActivity.java</h1>
<p>Create an Activity that will grab the information from your objects to whatever you want. In my case, I just display it using Logcat:</p>
<pre class="brush: java; title: ; notranslate">
public class TestActivity extends Activity {
	/** Called when the activity is first created. */
	private final String TAG = &quot;TAG&quot;;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		/**I instantiate my class XmlSAXParser and give it the file location and an start element tag*/
		XmlSAXParser myXMLParser = new XmlSAXParser(&quot;/sdcard/test.xml&quot;,&quot;GAMES&quot;);

		/**run the parser calling the method runParser()*/
		myXMLParser.runParser();

		/**I create a class ContentObjects that holds all my objects*/
		List&lt;ContentObject&gt; tempList;

		/**get the Parsed data from myXMLParser*/
		tempList=myXMLParser.getParsedData();

		Log.i(TAG,&quot;Action objects are: &quot;+tempList.size());
		Log.i(TAG,&quot;myXMLParser has: &quot;+myXMLParser.myContentObjects.size());

		/**iterate through the parsed objects contained in my XML using the Iterator class*/
		Iterator it = myXMLParser.myContentObjects.iterator();
		while(it.hasNext()) {
			ContentObject tempEmp = (ContentObject) it.next();
			Log.i(TAG,&quot;This is an object&quot;);
			Log.i(TAG,&quot;Name: &quot;+tempEmp.getName());
			Log.i(TAG,&quot;Image location: &quot;+tempEmp.getLocationImage());
			Log.i(TAG,&quot;Description: &quot;+tempEmp.getDescription());
		}
	}
}
</pre>
<p>Ok, so one comment above says I create a class contentObjects that holds all my objects. I meant, I create an instance of.</p>
<p>Once I run the parser, the myXMLParser object contains all the information I need and I use myXMLParser.getParsedData() to pass it down to a list which I itterate through and display the information.</p>
<p>If you use this code, make sure to create the XmlSAXParser object in a method so that when the method is finished, the object is destroyed and you will not have it in memory somewhere doing nothing useful.</p>
<p>Well hope you understand all of this, if you dont, feel free to drop me a comment! Enjoy!</p>
<p>If you would like to display the results in a ListView, I suggest you look at my tutorials for <a href="http://adblogcat.com/parse-json-data-from-a-web-server-and-display-on-listview/" title="JSON">JSON</a> and/or <a href="http://adblogcat.com/sqlite-database/" title="SQLite database">SQLite</a></p>
<p><b>Alternative</b><br />
I was asked, what if you need to grab the xml file from the res folder?</p>
<p>If you want it to put the xml into a project folder, you must change the implementation of the XmlSAXParser. The constructor in XMLSAXParser will be:</p>
<pre class="brush: java; title: ; notranslate">
public XmlSAXParser(InputStream location, String selection){
mLocationStream = location;
mSelection = selection;
}
</pre>
<p>Then you need to change RunParser method:</p>
<pre class="brush: java; title: ; notranslate">
public void runParser(){
     try{
          SAXParserFactory spf = SAXParserFactory.newInstance();
          SAXParser sp = spf.newSAXParser();
          XMLReader xr = sp.getXMLReader();
          xr.setContentHandler(this);
          xr.parse(new InputSource(mLocationStream));
     } catch (Exception e) {
     Log.i(TAG,&quot;XML Pasing Excpetion = &quot; + e);
     System.exit(-1);
     }
}
</pre>
<p>So that it takes an InputStream directly, not a FileInputStream that is created from the string path mLocation.</p>
<p>Finally, in TestActivity get the resource and give it to your constructor:</p>
<pre class="brush: java; title: ; notranslate">
InputStream resource = this.getResources().openRawResource(R.raw.test);
XmlSAXParser myXMLParser = new XmlSAXParser(resource,&quot;GAMES&quot;);
</pre>
<p><script type="text/javascript"><!--
google_ad_client = "ca-pub-1316223412202970";
/* 300_250_medium_rectangle_custom */
google_ad_slot = "1912768919";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://adblogcat.com/android-sax-xml-parsing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SQLite database</title>
		<link>http://adblogcat.com/sqlite-database/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=sqlite-database</link>
		<comments>http://adblogcat.com/sqlite-database/#comments</comments>
		<pubDate>Fri, 17 Feb 2012 17:45:19 +0000</pubDate>
		<dc:creator>guitarbaka</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[SQLite]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[sqlite]]></category>

		<guid isPermaLink="false">http://adblogcat.com/?p=239</guid>
		<description><![CDATA[This article describes how to create a project using an SQLite database. Most online tutorials show how to input one value. Here I will create a database of users with three values: first name, last name and age. This is &#8230; <a href="http://adblogcat.com/sqlite-database/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="tall" count="1" href="http://adblogcat.com/sqlite-database/"></g:plusone></div><p id="top" /><a href="http://adblogcat.com/wp-content/uploads/2012/02/AlertDialog.png"><img class="alignleft size-medium wp-image-242" title="AlertDialog" src="http://adblogcat.com/wp-content/uploads/2012/02/AlertDialog-180x300.png" alt="" width="180" height="300" /></a>This article describes how to create a project using an SQLite database. Most online tutorials show how to input one value. Here I will create a database of users with three values: first name, last name and age. This is then displayed in a ListView. This article includes adding and deleting users, using a Cursor, dynamically loading data to a ListView and using an AlertDialog to input user information.<br />
<span id="more-239"></span></p>
<p>The source code can be downloaded <a href="http://code.google.com/p/ece301-examples/downloads/detail?name=MySQLiteExample.zip&amp;can=2&amp;q=">HERE</a></p>
<p>Fist, we define the main.xml file to be used:</p>
<pre class="brush: java; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
	android:layout_width=&quot;fill_parent&quot; android:layout_height=&quot;fill_parent&quot;
	android:orientation=&quot;vertical&quot;&gt;
	&lt;LinearLayout android:id=&quot;@+id/group&quot;
		android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot;&gt;
		&lt;Button android:id=&quot;@+id/add&quot; android:layout_width=&quot;wrap_content&quot;
			android:layout_height=&quot;wrap_content&quot; android:text=&quot;Add New&quot; /&gt;
		&lt;Button android:id=&quot;@+id/delete&quot; android:layout_width=&quot;wrap_content&quot;
			android:layout_height=&quot;wrap_content&quot; android:text=&quot;Delete First&quot; /&gt;
	&lt;/LinearLayout&gt;
	&lt;ListView android:id=&quot;@android:id/list&quot; android:layout_width=&quot;fill_parent&quot;
		android:layout_height=&quot;wrap_content&quot; /&gt;
&lt;/LinearLayout&gt;
</pre>
<p>For the alert dialog, we need to create another XML file called newuser.xml in order to insert new users into our database:</p>
<pre class="brush: java; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
	android:layout_width=&quot;fill_parent&quot; android:layout_height=&quot;fill_parent&quot;
	android:orientation=&quot;vertical&quot;&gt;
	&lt;LinearLayout android:layout_width=&quot;wrap_content&quot;
		android:layout_height=&quot;wrap_content&quot; android:orientation=&quot;horizontal&quot;&gt;
		&lt;TextView android:layout_width=&quot;wrap_content&quot;
			android:layout_height=&quot;wrap_content&quot; android:text=&quot;First Name:&quot; /&gt;
		&lt;EditText android:id=&quot;@+id/first_name&quot; android:layout_width=&quot;wrap_content&quot;
			android:layout_height=&quot;wrap_content&quot; /&gt;
	&lt;/LinearLayout&gt;
	&lt;LinearLayout android:layout_width=&quot;wrap_content&quot;
		android:layout_height=&quot;wrap_content&quot; android:orientation=&quot;horizontal&quot;&gt;
		&lt;TextView android:layout_width=&quot;wrap_content&quot;
			android:layout_height=&quot;wrap_content&quot; android:text=&quot;Last Name:&quot; /&gt;
		&lt;EditText android:id=&quot;@+id/last_name&quot; android:layout_width=&quot;wrap_content&quot;
			android:layout_height=&quot;wrap_content&quot; /&gt;
	&lt;/LinearLayout&gt;
	&lt;LinearLayout android:layout_width=&quot;wrap_content&quot;
		android:layout_height=&quot;wrap_content&quot; android:orientation=&quot;horizontal&quot;&gt;
		&lt;TextView android:layout_width=&quot;wrap_content&quot;
			android:layout_height=&quot;wrap_content&quot; android:text=&quot;Age:&quot; /&gt;
		&lt;EditText android:id=&quot;@+id/age_age&quot; android:layout_width=&quot;wrap_content&quot;
			android:layout_height=&quot;wrap_content&quot; /&gt;
	&lt;/LinearLayout&gt;
&lt;/LinearLayout&gt;
</pre>
<h1>Create MYSQLiteHelper.java</h1>
<p>Now lets create a class MYSQLiteHelper that extends SQLiteOpenHelper and paste the code below:</p>
<pre class="brush: java; title: ; notranslate">
public class MySQLiteHelper extends SQLiteOpenHelper {

 public static final String TABLE_USERS = &quot;users&quot;;
 public static final String COLUMN_ID = &quot;_id&quot;;
 public static final String COLUMN_FIRST_NAME = &quot;firstname&quot;;
 public static final String COLUMN_LAST_NAME = &quot;lastname&quot;;
 public static final String COLUMN_AGE = &quot;age&quot;;

 private static final String DATABASE_NAME = &quot;users.db&quot;;
 private static final int DATABASE_VERSION = 1;

 // Database creation sql statement
 private static final String DATABASE_CREATE = &quot;create table &quot;
 + TABLE_USERS + &quot;( &quot; + COLUMN_ID
 + &quot; integer primary key autoincrement, &quot; + COLUMN_FIRST_NAME
 + &quot; text not null,&quot; + COLUMN_LAST_NAME + &quot; text not null,&quot; +
 COLUMN_AGE + &quot; text not null);&quot;;

 public MySQLiteHelper(Context context) {
 super(context, DATABASE_NAME, null, DATABASE_VERSION);
 }

 @Override
 public void onCreate(SQLiteDatabase db) {
 db.execSQL(DATABASE_CREATE);

 }

 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 db.execSQL(&quot;DROP TABLE IF EXISTS &quot;+TABLE_USERS);
 onCreate(db);

 }

}
</pre>
<p>The static final Strings represent the values of the database. Clearly you can see that my database&#8217;s name is users.db, I will create a table called &#8220;users&#8221;, with three columns, &#8220;firstname&#8221;, &#8220;lastname&#8221; and &#8220;age&#8221;.</p>
<p>IMPORTANT &#8212; COLUMN_ID = &#8220;_id&#8221; NEEDS TO BE INCLUDED FOR ANDROID DATABASES TO WORK PROPERLY.</p>
<p>For those that do not know mysql syntax, the String DATABASE_CREATE is just creating a TABLE (should name it TABLE_CREATE?). It is creating the structure of the database for adding values. Most importantly take close attention on how the columns are added:</p>
<pre class="brush: java; title: ; notranslate">
String DATABASE_CREATE = &quot;create table &quot;
			+ TABLE_USERS + &quot;( &quot; + COLUMN_ID
			+ &quot; integer primary key autoincrement, &quot; + COLUMN_FIRST_NAME
			+ &quot; text not null,&quot; + COLUMN_LAST_NAME + &quot; text not null,&quot; +
			COLUMN_AGE + &quot; text not null);&quot;;
</pre>
<p>SQLite syntax:</p>
<pre class="brush: sql; title: ; notranslate">
create table users(_id integer primary key autoincrement, firstname text not null, lastname text not null, age text not null);
</pre>
<p><script type="text/javascript"><!--
google_ad_client = "ca-pub-1316223412202970";
/* 300_250_medium_rectangle_custom */
google_ad_slot = "1912768919";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>
<p>If you want to create more tables or columns, write it out first in SQLite syntax then turn it to a string, for example:</p>
<pre class="brush: sql; title: ; notranslate">
create table workers(_id integer primary key autoincrement, firstname text not null, lastname text not null, age text not null, work_id text not null,
	work_extension);
</pre>
<p>In java, this would be:</p>
<pre class="brush: java; title: ; notranslate">
public static final String TABLE_WORKERS = &quot;workers&quot;
public static final String COLUMN_ID = &quot;_id&quot;;
public static final String COLUMN_FIRST_NAME = &quot;firstname&quot;;
public static final String COLUMN_LAST_NAME = &quot;lastname&quot;;
public static final String COLUMN_AGE = &quot;age&quot;;
public static final String COLUMN_WORK_ID = &quot;work_id&quot;;
public static final String COLUMN_WORK_EXTENSION = &quot;work_extension&quot;;

String DATABASE_CREATE = &quot;create table &quot;
			+ TABLE_WORKERS + &quot;( &quot; + COLUMN_ID
			+ &quot; integer primary key autoincrement, &quot; + COLUMN_FIRST_NAME
			+ &quot; text not null,&quot; + COLUMN_LAST_NAME + &quot; text not null,&quot;
			+ COLUMN_AGE + &quot; text not null,&quot; + COLUMN_WORK_ID + &quot;text not null,&quot;
			+ COLUMN_WORK_EXTENSION + &quot;text not null);&quot;;
</pre>
<p>I thought people might be confused as to how to create more columns, so there you go!</p>
<p>The methods that follow are just to create, update the database.</p>
<h1>Create Users.java</h1>
<p>Now create another class Users.java:</p>
<pre class="brush: java; title: ; notranslate">
public class Users {

	private long mId;
	private String mFirstName;
	private String mLastName;
	private String mAge;

	public long getmId() {
		return mId;
	}
	public void setmId(long mId) {
		this.mId = mId;
	}
	public String getmFirstName() {
		return mFirstName;
	}
	public void setmFirstName(String mFirstName) {
		this.mFirstName = mFirstName;
	}
	public String getmLastName() {
		return mLastName;
	}
	public void setmLastName(String mLastName) {
		this.mLastName = mLastName;
	}
	public String getmAge() {
		return mAge;
	}
	public void setmAge(String mAge) {
		this.mAge = mAge;
	}

	@Override
	public String toString(){
		return mFirstName+&quot; &quot;+mLastName+&quot;;&quot;+mAge;

	}

}
</pre>
<p>What this class will do is keep user information for first,last name and age that will be added to both the database and the Adapter of the ListView, thus the get and set methods. The last method is very important, public String toString() is what the ListView&#8217;s Adapter will use to display the information in the ListView.</p>
<h1>Create DataSource.java</h1>
<p>Create another class DataSource.java and paste the below:</p>
<pre class="brush: plain; title: ; notranslate">
public class DataSource {

	private SQLiteDatabase mSQLiteDatabase;
	private MySQLiteHelper mSQLiteHelper;

	private String[] mAllColumns = {MySQLiteHelper.COLUMN_ID,
			MySQLiteHelper.COLUMN_FIRST_NAME,
			MySQLiteHelper.COLUMN_LAST_NAME,
			MySQLiteHelper.COLUMN_AGE};

	public DataSource (Context context){
		mSQLiteHelper = new MySQLiteHelper(context);
	}

	public void open() throws SQLiteException {
		mSQLiteDatabase = mSQLiteHelper.getWritableDatabase();
	}

	public void close() {
		mSQLiteHelper.close();
	}

	public void addUser(String firstname, String lastname, String age){
		ContentValues values = new ContentValues();
		values.put(MySQLiteHelper.COLUMN_FIRST_NAME, firstname);
		values.put(MySQLiteHelper.COLUMN_LAST_NAME, lastname);
		values.put(MySQLiteHelper.COLUMN_AGE, age);
		mSQLiteDatabase.insert(MySQLiteHelper.TABLE_USERS, null, values);
	}

	public void deleteUser(Users user){
		long id = user.getmId();
		mSQLiteDatabase.delete(MySQLiteHelper.TABLE_USERS,
				MySQLiteHelper.COLUMN_ID+ &quot; = &quot; + id, null);
	}
</pre>
<p>This class creates a SQLiteDatabase object and MySQLiteHelper object to manage the database. It will open the database (or create it if it is the first time) when we call the method open().</p>
<p>It also adds and removes users. It will add user by passing user information, which will come from our AlertDialog (explained later) or deletes the user by passing a Users object (from the class created above with getters and setters).</p>
<pre class="brush: java; title: ; notranslate">
	public List getAllUsers(){

		List  users = new ArrayList();

		Cursor cursor = mSQLiteDatabase.query(MySQLiteHelper.TABLE_USERS,
				mAllColumns, null, null, null, null, null);
		cursor.moveToFirst();
		while (!cursor.isAfterLast()){
			Users user = cursorToUser(cursor);
			users.add(user);
			cursor.moveToNext();
		}
		cursor.close();
		return users;
	}

	private Users cursorToUser(Cursor cursor) {
		Users user = new Users();
		user.setmId(cursor.getLong(0));
		user.setmFirstName(cursor.getString(1));
		user.setmLastName(cursor.getString(2));
		user.setmAge(cursor.getString(3));
		return user;
	}

}
</pre>
<p>Lastly we have a method to get a list of Users by using a cursor. When I query a database, the results are put into a Cursor. I use this cursor to extract the information (In this case the information is Users objects) and I use cursorToUser to transform the information to Users so that my ListView&#8217;s Adapter can add it to display.</p>
<h1>Create TestDatabaseActivity.java</h1>
<p>Finally, we add the last class, TestDatabaseActivity and extend ListActivity.</p>
<pre class="brush: java; title: ; notranslate">
public class TestDatabaseActivity extends ListActivity {

	private DataSource mDataSource;
	private Button mAddButton;
	private Button mDeleteButton;
	private Context mContext;
	private ArrayAdapter mAdapter;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		mContext = this;
		mAddButton = (Button) findViewById(R.id.add);
		mDeleteButton = (Button) findViewById(R.id.delete);
		mDeleteButton.setClickable(true);
		mDeleteButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				deleteFirst();
			}
			private void deleteFirst() {
				Users user = null;
				if (getListAdapter().getCount() &gt; 0){
					user = (Users) getListAdapter().getItem(0);
					mDataSource.deleteUser(user);
					mAdapter.remove(user);
					mAdapter.notifyDataSetChanged();
				}
			}
		});
		mAddButton.setClickable(true);
		mAddButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				inputUserInformation();
			}
		});
</pre>
<p>Simple enough I create button listeners to my add and delete buttons. For mAddButton I create a method inputUserInformation(). For mDeleteButton I create a method deleteFirst(). I am only deleting first element with this button. The deleteFirst() method simply look for the first Users element in my ArrayAdapter and remove it from both the database (by using DataSource.deleteUser(Users)) and from the ArrayAdapter list. We must call the notifyDataSetChanged() method so our ListView is updated.</p>
<pre class="brush: java; title: ; notranslate">
		mDataSource = new DataSource(this);
		mDataSource.open();

		mAdapter = new ArrayAdapter(
				this,android.R.layout.simple_list_item_1,
				mDataSource.getAllUsers());
				setListAdapter(mAdapter);
	}

	@Override
	protected void onResume() {
		mDataSource.open();
		super.onResume();
	}

	@Override
	protected void onPause() {
		mDataSource.close();
		super.onPause();
	}
</pre>
<p>Here I am just creating a DataSource object and passing it the activity context and opening the database. Also, I am binding the ArrayAdapter to the ListView and making sure that I close the database when onPause() is called and opening it again when onResume() is called. Now finally, the method to add to the database:</p>
<pre class="brush: java; title: ; notranslate">
	private void inputUserInformation() {
		LayoutInflater factory = LayoutInflater.from(this);
		final View textEntryView = factory.inflate(R.layout.newuser, null);

		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle(&quot;New User Information&quot;);
		alert.setMessage(&quot;Enter your information below&quot;);
		alert.setView(textEntryView);

		final EditText input1 = (EditText) textEntryView.findViewById(R.id.first_name);
		final EditText input2 = (EditText) textEntryView.findViewById(R.id.last_name);
		final EditText input3 = (EditText) textEntryView.findViewById(R.id.age_age);

		alert.setPositiveButton(&quot;New Account&quot;, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {

				String fName = input1.getText().toString();
				String lName = input2.getText().toString();
				String age = input3.getText().toString();

				if ((fName.length() &lt;=0) || (lName.length()&lt;=0) || (age.length()&lt;=0)){
                                    Toast toast = Toast.makeText(mContext,
							&quot;Please fill in all data and try again&quot;, Toast.LENGTH_SHORT);
					toast.show();
				}
				else{
					Users user = new Users();
					user.setmAge(age);
					user.setmFirstName(fName);
					user.setmLastName(lName);
					mDataSource.addUser(fName, lName, age);
					mAdapter.add(user);
					mAdapter.notifyDataSetChanged();
				}
			}
		});
		alert.setNegativeButton(&quot;Cancel&quot;, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
			}
		});
		alert.show();
	}
</pre>
<p>Here I use the newuser.xml file to create an AlertDialog where I can input user information just like I showed at the beginning of the tutorial. On positive button click I check that the data is not empty and if it is not, then I create a Users object, populate it with the first, last name and age and then pass it to DataSource.add(Users) and ArrayAdapter.add(Users), then I call notifyDataSetChanged() to update the ListView.</p>
<p>NOTE THAT ArrayAdapter IN TURN CALLS Users&#8217;s toString() method to display the data in the format I gave it:</p>
<pre class="brush: java; title: ; notranslate">
@Override
	public String toString(){
		return mFirstName+&quot; &quot;+mLastName+&quot;;&quot;+mAge;

	}
</pre>
<p>And that is all. Happy coding!<br />
<a href="http://adblogcat.com/wp-content/uploads/2012/02/ListView.png"><img class="alignleft size-medium wp-image-250" title="ListView" src="http://adblogcat.com/wp-content/uploads/2012/02/ListView-180x300.png" alt="" width="180" height="300" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://adblogcat.com/sqlite-database/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SSL Sockets Android and server using a certificate</title>
		<link>http://adblogcat.com/ssl-sockets-android-and-server-using-a-certificate/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=ssl-sockets-android-and-server-using-a-certificate</link>
		<comments>http://adblogcat.com/ssl-sockets-android-and-server-using-a-certificate/#comments</comments>
		<pubDate>Thu, 09 Feb 2012 23:58:46 +0000</pubDate>
		<dc:creator>guitarbaka</dc:creator>
				<category><![CDATA[Network]]></category>
		<category><![CDATA[SSL sockets]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[server]]></category>
		<category><![CDATA[socket]]></category>
		<category><![CDATA[ssl]]></category>
		<category><![CDATA[ssl socket]]></category>

		<guid isPermaLink="false">http://adblogcat.com/?p=203</guid>
		<description><![CDATA[This article describes how to create a secure socket from an android device to a server using a certificate. It explains how to create a key that Android can use, write a secure server socket, a client socket and send &#8230; <a href="http://adblogcat.com/ssl-sockets-android-and-server-using-a-certificate/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="tall" count="1" href="http://adblogcat.com/ssl-sockets-android-and-server-using-a-certificate/"></g:plusone></div><p id="top" /><a href="http://adblogcat.com/wp-content/uploads/2012/02/emulator.png"><img class="alignleft  wp-image-294" title="android_php_mysql" src="http://adblogcat.com/wp-content/uploads/2012/02/emulator.png" alt="" width="150" height="150" /></a>This article describes how to create a secure socket from an android device to a server using a certificate. It explains how to create a key that Android can use, write a secure server socket, a client socket and send information back and forth between them.</p>
<p>First we can start by downloading the apk file for android and the jar file for your computer (server) along with the correct secure certificate and another certificate to test that other certificates will not work. Download link: <a href="http://ece301-examples.googlecode.com/files/ssl_sockets.zip" target="_blank">http://ece301-examples.googlecode.com/files/ssl_sockets.zip</a></p>
<p>First I will go through the steps so you can see a working example before looking at the code.<br />
<span id="more-203"></span></p>
<p>The easiest way to test this:</p>
<p>1. First, make sure that you are using Wifi and that your laptop and your android device are both connected to the same Wifi.<br />
2. From a terminal, run sslsocket.jar with the port number and the whole path of the certificate. In my case:</p>
<pre class="brush: php; title: ; notranslate">
java -jar sslsocket.jar 9998 /home/juan/testserverkeys
</pre>
<p>3. Install the APK file in your android device. The certificate is inside the assets folder. When the screen comes up, you need to specify the IP address of your computer, the port number (I used 9998) and a message you like to send over. Then press the SEND button. Look at the image at the start of this article. Should look like that</p>
<p>In your server side you should see the following</p>
<p><a href="http://adblogcat.com/wp-content/uploads/2012/02/server.png"><img class="aligncenter  wp-image-294" title="android_server_ssl" src="http://adblogcat.com/wp-content/uploads/2012/02/server.png" alt="" width="300" height="48" /></a></p>
<p>Now if you use the wrong certificate:</p>
<pre class="brush: php; title: ; notranslate">
java -jar sslsocket.jar 9998 /home/juan/testserverWrongKey
</pre>
<p>You will get an I/O exception in your android application. Try it!<br />
<a href="http://adblogcat.com/wp-content/uploads/2012/02/device_wrongkey.png"><img class="aligncenter  wp-image-294" title="android bad ssl certificate" src="http://adblogcat.com/wp-content/uploads/2012/02/device_wrongkey.png" alt="" width="180" height="300" /></a><br />
And your server as well will give you an IO exception:<br />
<a href="http://adblogcat.com/wp-content/uploads/2012/02/server_wrongkey.png"><img class="aligncenter  wp-image-294" title="android bad ssl certificate" src="http://adblogcat.com/wp-content/uploads/2012/02/server_wrongkey.png" alt="" width="300" height="74" /></a></p>
<p>The rest of this article is available for $.99 cents. It has all the source code available to create the apk and jar file and it explains how to create the android SSL certificate as well as the server side certificate.</p>
<p>                <p class="cleeng-prompt">
            <span class="cleeng-firsttime">
                This article is exclusive, use Cleeng to view it in full.            </span>
            <span class="cleeng-nofirsttime" style="display:none">
                The rest of this article is exclusive, use Cleeng again to view it.            </span>
            <span class="cleeng-auth" style="display:none">
                The rest of this article is exclusive,                <span class="cleeng-username"></span>,
                click "buy" and view it instantly.            </span>
        </p>
        
        <div id="cleeng-layer-364446273" class="cleeng-layer" >
        <div class="cleeng-protected-content" id="cleeng-364446273" rel="203" >Exclusive content</div>
        <div class="cleeng-layer-left"></div>

        <div class="cleeng-text">
                        <div class="cleeng-noauth-bar">
                <span class="cleeng-welcome-firsttime">
                    Already have a Cleeng account?                </span>

                <span class="cleeng-welcome-nofirsttime" style="display:none">
                Welcome back!                </span>
                <a class="cleeng-hlink cleeng-login" href="javascript:">Log-in</a>
            </div>
            <div class="cleeng-auth-bar" style="display:none">
                <a class="cleeng-hlink cleeng-logout" href="#">Logout</a>
                Welcome, <a class="cleeng-username" href="http://cleeng.com/my-account"></a>            </div>

                        <div class="cleeng-publisher">
                <div class="cleeng-ajax-loader">&nbsp;</div>
                <img src="http://cleeng.com/media/users/942/770/747_mini.png"
                     alt=""
                     title="" />
            </div>


            <h2 class="cleeng-description">All articles you purchase here have a money back guarantee if you are not completely satisfied.</h2>
            <div class="cleeng-rating">
                <span>Customer rating:</span>
                <div class="cleeng-stars cleeng-stars-4"></div>
            </div>

            <span class="cleeng-free-content-views" style="display:none">
                Good news! You still have <span></span> free purchase(s).            </span>
        </div>
        <div class="cleeng-text-bottom">
            <div class="cleeng-textBottom">
                <div class="cleeng-purchaseInfo-grad">
                </div>
                <div class="cleeng-purchaseInfo">
                    <div class="cleeng-purchaseInfo-text">

                        
                                
                                <div class="cleeng-button cleeng-middle  register-and-read-for-free-364446273 by-free-364446273">
                                    Register and read for free                                 </div>

                                <div class="cleeng-button cleeng-middle  register-and-watch-for-free-364446273 by-free-364446273">
                                    Register and watch for free                                 </div>

                                <div class="cleeng-button cleeng-middle  register-and-access-for-free-364446273 by-free-364446273">
                                    Register and access for free                                 </div>

                                <div class="cleeng-button cleeng-middle  read-for-free-364446273 by-free-364446273">
                                    Read for free                                 </div>

                                <div class="cleeng-button cleeng-middle  watch-for-free-364446273 by-free-364446273">
                                    Watch for free                                 </div>

                                <div class="cleeng-button cleeng-middle  access-for-free-364446273 by-free-364446273">
                                    Access for free                                 </div>

                                <div class="cleeng-button cleeng-middle  buy-this-article-364446273">
                                    Buy this article                                     <span class="cleeng-price">$0.99</span>
                                </div>

                                <div class="cleeng-button cleeng-middle  buy-this-video-364446273">
                                    Buy this video                                     <span class="cleeng-price">$0.99</span>
                                </div>

                                <div  class="cleeng-button cleeng-middle   buy-this-item-364446273">
                                    Buy this item                                     <span class="cleeng-price">$0.99</span>
                                </div>

                                <div id="cleeng-subscribe-364446273" class="cleeng-subscribe cleeng-button"
                                     style="display:none">                                </div>

                                                                    <style>
                                        .read-for-free-364446273, .watch-for-free-364446273, .access-for-free-364446273, .register-and-read-for-free-364446273, .register-and-watch-for-free-364446273, .register-and-access-for-free-364446273, .buy-this-article-364446273, .buy-this-video-364446273, .buy-this-item-364446273{display:none}                                        .buy-this-article-364446273 {
                                            display:block;
                                        }
                                    </style>

                        
                    </div>
                </div>
                <div class="cleeng-whatsCleeng" style="width:171px">
                     <div style="cursor:pointer;width:155px;line-height:12px;background: url('http://cleeng.com/logo/cleeng-small-500.png?contentId=364446273') no-repeat right top" href="http://cleeng.com/what-is-cleeng">Powered by</div>    
                     
                </div>
            </div>
        </div>

        <div class="cleeng-layer-right"></div>
    </div>
    <div id="cleeng-nolayer-364446273" class="cleeng-nolayer" style="display:none">
                <div class="cleeng-nolayer-top">
                    <a href="http://cleeng.com">
                        <img src="http://adblogcat.com/wp-content/plugins/cleeng/img/cleeng-small.png" alt="Cleeng: Instant access to quality content" />
                    </a>
                    <div class="cleeng-auth-bar">
                        <a class="cleeng-hlink cleeng-logout" href="#">
                            Logout                        </a>
                        Welcome, <a class="cleeng-username" href="http://cleeng.com/my-account"></a>                    </div>
                </div>

                <div class="cleeng-content">
                 </div>

             <div class="cleeng-nolayer-bottom">

                <span  class="cleeng-rate" style="display:none">
                    Rate:                    <a href="#" class="cleeng-icon cleeng-vote-liked">&nbsp;</a>
                    <a href="#" class="cleeng-icon cleeng-vote-didnt-like">&nbsp;</a>
                </span>
                <span style="float:left" class="cleeng-rating">
                    <!--Customer rating:-->
                    <span class="cleeng-stars cleeng-stars-4"></span>
                </span>
                <span class="cleeng-share">
                    <!--Share:-->
                    <a class="cleeng-icon cleeng-facebook" href="#">&nbsp;</a>
                    <a class="cleeng-icon cleeng-twitter" href="#">&nbsp;</a>
                    <a class="cleeng-icon cleeng-email" href="mailto:?subject=&amp;body=">&nbsp;</a>
                    <!--<span class="cleeng-referral-url-label">URL:</span>-->
                    <span class="cleeng-referral-url"></span>
                    <span class="cleeng-icon cleeng-copy">&nbsp;</span>
                </span>
                <span class="cleeng-referral-rate">
                    Earn: <span>5%</span> commission                </span>
              </div>
          </div>

    </p>
]]></content:encoded>
			<wfw:commentRss>http://adblogcat.com/ssl-sockets-android-and-server-using-a-certificate/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A camera preview with a bounding box like Google goggles</title>
		<link>http://adblogcat.com/a-camera-preview-with-a-bounding-box-like-google-goggles/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=a-camera-preview-with-a-bounding-box-like-google-goggles</link>
		<comments>http://adblogcat.com/a-camera-preview-with-a-bounding-box-like-google-goggles/#comments</comments>
		<pubDate>Thu, 09 Feb 2012 22:47:21 +0000</pubDate>
		<dc:creator>guitarbaka</dc:creator>
				<category><![CDATA[Camera]]></category>
		<category><![CDATA[Canvas]]></category>
		<category><![CDATA[Touch Events]]></category>
		<category><![CDATA[android bounding box]]></category>
		<category><![CDATA[bounding box]]></category>
		<category><![CDATA[camera preview]]></category>
		<category><![CDATA[canvas]]></category>
		<category><![CDATA[google goggles]]></category>
		<category><![CDATA[TouchEvent]]></category>

		<guid isPermaLink="false">http://adblogcat.com/?p=178</guid>
		<description><![CDATA[This article describes how to draw a bounding box on top of a camera preview to capture part of the image just like Google goggles does. This article mainly involves looking at a SurfaceView for generating a camera view and &#8230; <a href="http://adblogcat.com/a-camera-preview-with-a-bounding-box-like-google-goggles/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="tall" count="1" href="http://adblogcat.com/a-camera-preview-with-a-bounding-box-like-google-goggles/"></g:plusone></div><p id="top" />This article describes how to draw a bounding box on top of a camera preview to capture part of the image just like Google goggles does. This article mainly involves looking at a SurfaceView for generating a camera view and a View to create a canvas and draw on top of the camera view. Also shows how to use the onTouchInterceptEvent to pass touch events to lower Views. Android 2.2 API needs to be used for this.<br />
<span id="more-178"></span><br />
After seeing Google goggle&#8217;s implementation, I thought there would be some API to do this, but I could not find any. I then decided to create my own. I did this for my app: <a href="https://market.android.com/details?id=com.translanguage.free.version&amp;hl=en">Translanguage OCR</a>.</p>
<p>You can download the source <a href="http://code.google.com/p/ece301-examples/downloads/detail?name=CameraPreview.zip&amp;can=2&amp;q=#makechanges">HERE</a><br />
Password is: preview</p>
<h1>Create the Project</h1>
<p>Create a new android project. Here create the classes: CameraPreview, Preview, TouchView and Wait. Also you need two images, camera.png and corners.png. You can save them from here:</p>
<p><a href="http://adblogcat.com/wp-content/uploads/2012/02/corners.png"><img class="alignnone size-full wp-image-179" title="corners" src="http://adblogcat.com/wp-content/uploads/2012/02/corners.png" alt="" width="20" height="20" /></a></p>
<p><a href="http://adblogcat.com/wp-content/uploads/2012/02/camera.png"><br />
<img class="alignnone size-full wp-image-180" title="camera" src="http://adblogcat.com/wp-content/uploads/2012/02/camera.png" alt="" width="96" height="96" /></a></p>
<p>Your folder structure will look something like this:<br />
<a href="http://adblogcat.com/wp-content/uploads/2012/02/eclipse_view.png"><img class="alignnone size-medium wp-image-182" title="eclipse_view" src="http://adblogcat.com/wp-content/uploads/2012/02/eclipse_view-176x300.png" alt="" width="176" height="300" /></a></p>
<p>Open the manifest and add the following permissions:</p>
<pre class="brush: java; title: ; notranslate">
&lt;uses-permission android:name=&quot;android.permission.CAMERA&quot; /&gt;
&lt;uses-feature android:name=&quot;android.hardware.camera&quot; /&gt;
&lt;uses-feature android:name=&quot;android.hardware.camera.autofocus&quot; /&gt;
&lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot; /&gt;
</pre>
<p>Now open the main.xml file and add the following:</p>
<pre class="brush: java; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
	android:orientation=&quot;vertical&quot; android:layout_width=&quot;fill_parent&quot;
	android:layout_height=&quot;fill_parent&quot;&gt;
	&lt;com.camera.preview.Preview android:id=&quot;@+id/preview&quot;
		android:layout_width=&quot;fill_parent&quot; android:layout_height=&quot;fill_parent&quot;&gt;
	&lt;/com.camera.preview.Preview&gt;

	&lt;com.camera.preview.TouchView android:id=&quot;@+id/left_top_view&quot;
		android:layout_width=&quot;fill_parent&quot; android:layout_height=&quot;fill_parent&quot;&gt;
	&lt;/com.camera.preview.TouchView&gt;

	&lt;ImageView android:id=&quot;@+id/startcamerapreview&quot; android:src=&quot;@drawable/camera&quot;
		android:layout_width=&quot;fill_parent&quot; android:layout_height=&quot;wrap_content&quot;
		android:layout_alignParentBottom=&quot;true&quot;
		android:layout_alignParentRight=&quot;true&quot; /&gt;
&lt;/RelativeLayout&gt;
</pre>
<p>Here we are adding a Preview and a TouchView which we will create so that the camera is used for a camera preview and a View to draw on top of it.</p>
<h1>Wait.java</h1>
<p>Now we will write to the Wait.java class. This is just a simple thread to wait some period of time. This will be useful for the autofocus.</p>
<pre class="brush: java; title: ; notranslate">
public class Wait {
	public static void oneSec() {
		try {
			Thread.currentThread().sleep(1000);
		}
		catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	public static void manySec(long s) {
		try {
			Thread.currentThread().sleep(s * 1000);
		}
		catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
</pre>
<h1>Preview.java</h1>
<p>Now open Preview.java and extend SurfaceView and implement SurfaceHolder.CallBack. Three methods will be created: surfaceCreated, surfaceDestroyed, surfaceChanged. </p>
<p>Preview.java is used to open a camera preview. It uses hardware.Camera and a SurfaceView to display the camera&#8217;s view on the screen. Now to write some code. The constructors and some extra methods:</p>
<pre class="brush: java; title: ; notranslate">
class Preview extends SurfaceView implements SurfaceHolder.Callback {	

	private SurfaceHolder mHolder;
	private Camera mCamera;
	private Camera.Parameters mParameters;
	private byte[] mBuffer;

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

	public Preview(Context context) {
		super(context);
		init();
	}

	public void init() {
		// Install a SurfaceHolder.Callback so we get notified when the
		// underlying surface is created and destroyed.
		mHolder = getHolder();
		mHolder.addCallback(this);
		mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	}
</pre>
<p>This is a pretty standard way of getting a Holder to hold the camera preview. The purpose of this view is to get the view onto the screen and be able to take the picture and save it. For this we need another method:</p>
<pre class="brush: java; title: ; notranslate">
	public Bitmap getPic(int x, int y, int width, int height) {
		System.gc();
		Bitmap b = null;
		Size s = mParameters.getPreviewSize();

		YuvImage yuvimage = new YuvImage(mBuffer, ImageFormat.NV21, s.width, s.height, null);
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		yuvimage.compressToJpeg(new Rect(x, y, width, height), 100, outStream); // make JPG
		b = BitmapFactory.decodeByteArray(outStream.toByteArray(), 0, outStream.size());
		if (b != null) {
			//Log.i(TAG, &quot;getPic() WxH:&quot; + b.getWidth() + &quot;x&quot; + b.getHeight());
		} else {
			//Log.i(TAG, &quot;getPic(): Bitmap is null..&quot;);
		}
		yuvimage = null;
		outStream = null;
		System.gc();
		return b;
	}
</pre>
<p>This method is the one that will get an area of the image, or a set of coordinates in the image, and turn it into a Bitmap. The CameraPreview class will explain how the set of coordinates is taken. The reason API 2.2 is needed is because of the YuvImage class. This class is crucial for what we are trying to do here. YuvImage is used, compressed to jpeg and turned to bitmap.</p>
<p>In order to keep the image, we need to set up a buffer. This will ensure that when the image is captured, the buffer is big enough to hold the data. </p>
<pre class="brush: java; title: ; notranslate">
	private void updateBufferSize() {
		mBuffer = null;
		System.gc();
		// prepare a buffer for copying preview data to
		int h = mCamera.getParameters().getPreviewSize().height;
		int w = mCamera.getParameters().getPreviewSize().width;
		int bitsPerPixel =
                     ImageFormat.getBitsPerPixel(mCamera.getParameters().getPreviewFormat());
		mBuffer = new byte[w * h * bitsPerPixel / 8];
		//Log.i(&quot;surfaceCreated&quot;, &quot;buffer length is &quot; + mBuffer.length + &quot; bytes&quot;);
	}
</pre>
<p>Now the methods we need to Override:</p>
<pre class="brush: java; title: ; notranslate">
	public void surfaceCreated(SurfaceHolder holder) {
		// The Surface has been created, acquire the camera and tell it where to draw.
		try {
			mCamera = Camera.open(); // WARNING: without permission in Manifest.xml, crashes
		}
		catch (RuntimeException exception) {
			//Log.i(TAG, &quot;Exception on Camera.open(): &quot; + exception.toString());
			Toast.makeText(getContext(), &quot;Camera broken, quitting <img src='http://adblogcat.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> &quot;,Toast.LENGTH_LONG).show();
			// TODO: exit program
		}

		try {
			mCamera.setPreviewDisplay(holder);
			//updateBufferSize();
			mCamera.addCallbackBuffer(mBuffer); // where we'll store the image data
			mCamera.setPreviewCallbackWithBuffer(new PreviewCallback() {
				public synchronized void onPreviewFrame(byte[] data, Camera c) {

					if (mCamera != null) { // there was a race condition when onStop() was called..
						mCamera.addCallbackBuffer(mBuffer); // it was consumed by the call, add it back
					}
				}
			});
		} catch (Exception exception) {
			//Log.e(TAG, &quot;Exception trying to set preview&quot;);
			if (mCamera != null){
				mCamera.release();
				mCamera = null;
			}
			// TODO: add more exception handling logic here
		}
	}
</pre>
<p>When the surface is created, this method is called. Here we have to open the hardware.Camera and set a Preview display (thus camera preview), set the buffer and start receiving data. Using hardware.Camera is sometimes annoying because you have to be sure to release the camera or you will have problems with your application or even other applications that need to access the camera after you are done. I remember having to reboot my phone a few times because I was not releasing the camera.</p>
<p>When SurfaceDestroyed gets called, we stop the preview let go of all the resources:</p>
<pre class="brush: java; title: ; notranslate">
	public void surfaceDestroyed(SurfaceHolder holder) {
		// Surface will be destroyed when we return, so stop the preview.
		// Because the CameraDevice object is not a shared resource, it's very
		// important to release it when the activity is paused.
		//Log.i(TAG,&quot;SurfaceDestroyed being called&quot;);
		mCamera.stopPreview();
		mCamera.release();
		mCamera = null;
	}
</pre>
<p>On SurfaceChanged, we set the parameters for the camera, which in this case is landscape. At first I initially set the preview size by using some algorithm from google that didn&#8217;t work well, so I just removed it and let it grab the current one set, and it seems to work very well. This is also where updateBufferSize() is called so that the buffer size is set for the next picture to be taken and we don&#8217;t get some error for running out of memory. And another method to get the camera parameters.</p>
<pre class="brush: java; title: ; notranslate">
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
		//Log.i(TAG, &quot;Preview: surfaceChanged() - size now &quot; + w + &quot;x&quot; + h);
		// Now that the size is known, set up the camera parameters and begin
		// the preview.
		try {
			mParameters = mCamera.getParameters();
			mParameters.set(&quot;orientation&quot;,&quot;landscape&quot;);
			for (Integer i : mParameters.getSupportedPreviewFormats()) {
				//Log.i(TAG, &quot;supported preview format: &quot; + i);
			} 

			List&lt;Size&gt; sizes = mParameters.getSupportedPreviewSizes();
			for (Size size : sizes) {
				//Log.i(TAG, &quot;supported preview size: &quot; + size.width + &quot;x&quot; + size.height);
			}
			mCamera.setParameters(mParameters); // apply the changes
		} catch (Exception e) {
			// older phone - doesn't support these calls
		}

		//updateBufferSize(); // then use them to calculate

		Size p = mCamera.getParameters().getPreviewSize();
		//Log.i(TAG, &quot;Preview: checking it was set: &quot; + p.width + &quot;x&quot; + p.height); // DEBUG
		mCamera.startPreview();
	}

	public Parameters getCameraParameters(){
		return mCamera.getParameters();
	}
</pre>
<p>Finally to set autoFocus and Flash we have two methods:</p>
<pre class="brush: java; title: ; notranslate">
	public void setCameraFocus(AutoFocusCallback autoFocus){
		if (mCamera.getParameters().getFocusMode().equals(mCamera.getParameters().FOCUS_MODE_AUTO) ||
				mCamera.getParameters().getFocusMode().equals(mCamera.getParameters().FOCUS_MODE_MACRO)){
			mCamera.autoFocus(autoFocus);
		}
	}

	public void setFlash(boolean flash){
		Toast.makeText(Preview.this.getContext(), &quot;Flash is: &quot;+mParameters.getFlashMode(), Toast.LENGTH_LONG).show();
		if (flash){
			mParameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
			mCamera.setParameters(mParameters);
		}
		else{
			mParameters.setFlashMode(Parameters.FLASH_MODE_OFF);
			mCamera.setParameters(mParameters);
		}
	}
</pre>
<h1>TouchView.java</h1>
<p>Things get progressively more difficult. This class is pretty important and the class that will create a canvas to draw on top of the camera preview. It implements View.<br />
I will create Drawables for the corners of the bounding box and lines (Paint) to connect these boxes.</p>
<p>The constructor initializes our boxes and lines. The onDraw method draws them on top of the camera preview with the positions updated.<br />
This update happens when the method invalidate() is called. Then the touch event method takes care of moving the bounding box.<br />
First lets look at the data objects we need.</p>
<pre class="brush: java; title: ; notranslate">
public class TouchView extends View {

	private Drawable mLeftTopIcon;
	private Drawable mRightTopIcon;
	private Drawable mLeftBottomIcon;
	private Drawable mRightBottomIcon;

	private boolean mLeftTopBool = false;
	private boolean mRightTopBool = false;
	private boolean mLeftBottomBool = false;
	private boolean mRightBottomBool = false;

	// Starting positions of the bounding box

	private float mLeftTopPosX = 30;
	private float mLeftTopPosY = 120;

	private float mRightTopPosX = 150;
	private float mRightTopPosY = 120;

	private float mLeftBottomPosX = 30;
	private float mLeftBottomPosY = 200;

	private float mRightBottomPosX = 150;
	private float mRightBottomPosY = 200;
	private float mPosX;
	private float mPosY;

	private float mLastTouchX;
	private float mLastTouchY;

	private Paint topLine;
	private Paint bottomLine;
	private Paint leftLine;
	private Paint rightLine;

	private Rect buttonRec;

	private int mCenter;

	private static final int INVALID_POINTER_ID = -1;
	private int mActivePointerId = INVALID_POINTER_ID;

	// you can ignore this for this code
	private ScaleGestureDetector mScaleDetector;
	private float mScaleFactor = 1.f;
</pre>
<p>Paints will draw lines, Drawables are the corners, floats are the locations and Booleans are so that we can only move one corner at a time.</p>
<p>The constructors set the line colors, size, etc. It also sets the positions of the paints.</p>
<pre class="brush: plain; title: ; notranslate">
	public TouchView(Context context){
		super(context);
		init(context);
	}

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

	public TouchView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(context);
	}

	private void init(Context context) {

		// I need to create lines for the bouding box to connect

		topLine = new Paint();
		bottomLine = new Paint();
		leftLine = new Paint();
		rightLine = new Paint();

		setLineParameters(Color.WHITE,2);

		// Here I grab the image that will work as the corners of the bounding
		// box and set their positions.

		mLeftTopIcon = context.getResources().getDrawable(R.drawable.corners);

		mCenter = mLeftTopIcon.getMinimumHeight()/2;
		mLeftTopIcon.setBounds((int)mLeftTopPosX, (int)mLeftTopPosY,
				mLeftTopIcon.getIntrinsicWidth()+(int)mLeftTopPosX,
				mLeftTopIcon.getIntrinsicHeight()+(int)mLeftTopPosY);

		mRightTopIcon = context.getResources().getDrawable(R.drawable.corners);
		mRightTopIcon.setBounds((int)mRightTopPosX, (int)mRightTopPosY,
				mRightTopIcon.getIntrinsicWidth()+(int)mRightTopPosX,
				mRightTopIcon.getIntrinsicHeight()+(int)mRightTopPosY);

		mLeftBottomIcon = context.getResources().getDrawable(R.drawable.corners);
		mLeftBottomIcon.setBounds((int)mLeftBottomPosX, (int)mLeftBottomPosY,
				mLeftBottomIcon.getIntrinsicWidth()+(int)mLeftBottomPosX,
				mLeftBottomIcon.getIntrinsicHeight()+(int)mLeftBottomPosY);

		mRightBottomIcon = context.getResources().getDrawable(R.drawable.corners);
		mRightBottomIcon.setBounds((int)mRightBottomPosX, (int)mRightBottomPosY,
				mRightBottomIcon.getIntrinsicWidth()+(int)mRightBottomPosX,
				mRightBottomIcon.getIntrinsicHeight()+(int)mRightBottomPosY);
		// Create our ScaleGestureDetector
		mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());

	}

	private void setLineParameters(int color, float width){

		topLine.setColor(color);
		topLine.setStrokeWidth(width);

		bottomLine.setColor(color);
		bottomLine.setStrokeWidth(width);

		leftLine.setColor(color);
		leftLine.setStrokeWidth(width);

		rightLine.setColor(color);
		rightLine.setStrokeWidth(width);

	}
</pre>
<p>OnDraw draws the bounding box on top of the camera preview. invalidate() needs to be called every time an update happens. This is done in the Event Listeners.</p>
<pre class="brush: java; title: ; notranslate">
	public boolean onTouchEvent(MotionEvent ev) {
		final int action = ev.getAction();
		boolean intercept = true;

		switch (action) {

		case MotionEvent.ACTION_DOWN: {

			final float x = ev.getX();
			final float y = ev.getY();

			// in CameraPreview we have Rect rec. This is passed here to return
			// a false when the camera button is pressed so that this view ignores
			// the touch event.
			if ((x &gt;= buttonRec.left) &amp;&amp; (x &lt;=buttonRec.right) &amp;&amp; (y&gt;=buttonRec.top) &amp;&amp; (y&lt;=buttonRec.bottom)){
				intercept = false;
				break;
			}

			// is explained below, when we get to this method.
			manhattanDistance(x,y);

			// Remember where we started
			mLastTouchX = x;
			mLastTouchY = y;
			mActivePointerId = ev.getPointerId(0);
			break;
		}

		case MotionEvent.ACTION_MOVE: {

			final int pointerIndex = ev.findPointerIndex(mActivePointerId);
			final float x = ev.getX();
			final float y = ev.getY();
			//Log.i(TAG,&quot;x: &quot;+x);
			//Log.i(TAG,&quot;y: &quot;+y);

			// Only move if the ScaleGestureDetector isn't processing a gesture.
			// but we ignore here because we are not using ScaleGestureDetector.
			if (!mScaleDetector.isInProgress()) {
				final float dx = x - mLastTouchX;
				final float dy = y - mLastTouchY;

				mPosX += dx;
				mPosY += dy;

				invalidate();
			}

			// Calculate the distance moved
			final float dx = x - mLastTouchX;
			final float dy = y - mLastTouchY;

			// Move the object
			if (mPosX &gt;= 0 &amp;&amp; mPosX &lt;=800){
				mPosX += dx;
			}
			if (mPosY &gt;=0 &amp;&amp; mPosY &lt;= 480){
				mPosY += dy;
			}

			// while its being pressed n it does not overlap the bottom line or right line
			if (mLeftTopBool &amp;&amp; ((y+mCenter*2) &lt; mLeftBottomPosY) &amp;&amp; ((x+mCenter*2) &lt; mRightTopPosX)){
				if (dy != 0){
					mRightTopPosY = y;
				}
				if (dx != 0){
					mLeftBottomPosX = x;
				}
				mLeftTopPosX = x;//mPosX;
				mLeftTopPosY = y;//mPosY;
			}
			if (mRightTopBool &amp;&amp; ((y+mCenter*2) &lt; mRightBottomPosY) &amp;&amp; (x &gt; (mLeftTopPosX+mCenter*2))){
				if (dy != 0){
					mLeftTopPosY = y;
				}
				if (dx != 0){
					mRightBottomPosX = x;
				}
				mRightTopPosX = x;//mPosX;
				mRightTopPosY = y;//mPosY;
			}
			if (mLeftBottomBool &amp;&amp; (y &gt; (mLeftTopPosY+mCenter*2)) &amp;&amp; ((x +mCenter*2) &lt; mRightBottomPosX)){
				if (dx != 0){
					mLeftTopPosX = x;
				}
				if (dy != 0){
					mRightBottomPosY = y;
				}
				mLeftBottomPosX = x;
				mLeftBottomPosY = y;
			}
			if (mRightBottomBool &amp;&amp; (y &gt; (mLeftTopPosY+mCenter*2)) &amp;&amp; (x &gt; (mLeftBottomPosX+mCenter*2) )){
				if (dx != 0){
					mRightTopPosX = x;
				}
				if (dy != 0){
					mLeftBottomPosY = y;
				}
				mRightBottomPosX = x;
				mRightBottomPosY = y;
			}

			// Remember this touch position for the next move event
			mLastTouchX = x;
			mLastTouchY = y;

			// Invalidate to request a redraw
			invalidate();
			break;
		}
		case MotionEvent.ACTION_UP: {
			// when one of these is true, that means it can move when onDraw is called
			mLeftTopBool = false;
			mRightTopBool = false;
			mLeftBottomBool = false;
			mRightBottomBool = false;
			//mActivePointerId = INVALID_POINTER_ID;
			break;
		}

		case MotionEvent.ACTION_CANCEL: {
			mActivePointerId = INVALID_POINTER_ID;
			break;
		}

		case MotionEvent.ACTION_POINTER_UP: {
			// Extract the index of the pointer that left the touch sensor
			final int pointerIndex = (action &amp; MotionEvent.ACTION_POINTER_INDEX_MASK)
			&gt;&gt; MotionEvent.ACTION_POINTER_INDEX_SHIFT;
			final int pointerId = ev.getPointerId(pointerIndex);
			if (pointerId == mActivePointerId) {
				// This was our active pointer going up. Choose a new
				// active pointer and adjust accordingly.
				final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
				mLastTouchX = ev.getX(newPointerIndex);
				mLastTouchY = ev.getY(newPointerIndex);
				mActivePointerId = ev.getPointerId(newPointerIndex);
			}
			break;
		}
		}
		return intercept;
	}
</pre>
<p>Notice that I am returning intercept boolean. Why? Because I am using onInterceptTouchEvent on the CameraPreview.java class. This allows me to pass the touch event to lower Views of the GUI.</p>
<p>In order to identify which corner is being pressed I used simple math. I used the Manhattan distance to calculate when the user presses the screen, which of the corners it is close to and move it.</p>
<pre class="brush: java; title: ; notranslate">
	// Where the screen is pressed, calculate the distance closest to one of the 4 corners
	// so that it can get the pressed and moved. Only 1 at a time can be moved.
	private void manhattanDistance(float x, float y) {

		double leftTopMan = Math.sqrt(Math.pow((Math.abs((double)x-(double)mLeftTopPosX)),2)
				+ Math.pow((Math.abs((double)y-(double)mLeftTopPosY)),2));

		double rightTopMan = Math.sqrt(Math.pow((Math.abs((double)x-(double)mRightTopPosX)),2)
				+ Math.pow((Math.abs((double)y-(double)mRightTopPosY)),2));

		double leftBottomMan = Math.sqrt(Math.pow((Math.abs((double)x-(double)mLeftBottomPosX)),2)
				+ Math.pow((Math.abs((double)y-(double)mLeftBottomPosY)),2));

		double rightBottomMan = Math.sqrt(Math.pow((Math.abs((double)x-(double)mRightBottomPosX)),2)
				+ Math.pow((Math.abs((double)y-(double)mRightBottomPosY)),2));

		//Log.i(TAG,&quot;leftTopMan: &quot;+leftTopMan);
		//Log.i(TAG,&quot;RightTopMan: &quot;+rightTopMan);

		if (leftTopMan &lt; 50){
			mLeftTopBool = true;
			mRightTopBool = false;
			mLeftBottomBool = false;
			mRightBottomBool = false;
		}
		else if (rightTopMan &lt; 50){
			mLeftTopBool = false;
			mRightTopBool = true;
			mLeftBottomBool = false;
			mRightBottomBool = false;
		}
		else if (leftBottomMan &lt; 50){
			mLeftTopBool = false;
			mRightTopBool = false;
			mLeftBottomBool = true;
			mRightBottomBool = false;
		}
		else if (rightBottomMan &lt; 50){
			mLeftTopBool = false;
			mRightTopBool = false;
			mLeftBottomBool = false;
			mRightBottomBool = true;
		}

	}
</pre>
<p>Then I need the setters and getters for the corner positions and finally a method for invalidating the view. </p>
<pre class="brush: java; title: ; notranslate">
	public float getmLeftTopPosX(){
		return mLeftTopPosX;
	}
	public float getmLeftTopPosY(){
		return mLeftTopPosY;
	}
	public float getmRightTopPosX(){
		return mRightTopPosX;
	}
	public float getmRightTopPosY(){
		return mRightTopPosY;
	}
	public float getmLeftBottomPosX() {
		return mLeftBottomPosX;
	}
	public float getmLeftBottomPosY() {
		return mLeftBottomPosY;
	}
	public float getmRightBottomPosY() {
		return mRightBottomPosY;
	}
	public float getmRightBottomPosX() {
		return mRightBottomPosX;
	}
	public void setRec(Rect rec) {
		this.buttonRec = rec;
	}

	// calls the onDraw method, I used it in my app Translanguage OCR
	// because I have a thread that needs to invalidate, or redraw
	// you cannot call onDraw from a thread not the UI thread.
	public void setInvalidate() {
		invalidate();

	}
</pre>
<p>If you have followed me all this way, then lets move to the final class.</p>
<h1>CameraPreview.java</h1>
<p>This is the class that takes care of putting everything together and this is why its the last class to be explained.</p>
<pre class="brush: java; title: ; notranslate">
public class CameraPreview extends Activity implements SensorEventListener {

	private Preview mPreview;
	private ImageView mTakePicture;
	private TouchView mView;

	private boolean mAutoFocus = true;

	private boolean mFlashBoolean = false;

	private SensorManager mSensorManager;
	private Sensor mAccel;
	private boolean mInitialized = false;
	private float mLastX = 0;
	private float mLastY = 0;
	private float mLastZ = 0;
	private Rect rec = new Rect();

	private int mScreenHeight;
	private int mScreenWidth;

	private boolean mInvalidate = false;

	private File mLocation = new File(Environment.
			getExternalStorageDirectory(),&quot;test.jpg&quot;);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//Log.i(TAG, &quot;onCreate()&quot;);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		// display our (only) XML layout - Views already ordered
		setContentView(R.layout.main);

		// the accelerometer is used for autofocus
		mSensorManager = (SensorManager) getSystemService(Context.
				SENSOR_SERVICE);
		mAccel = mSensorManager.getDefaultSensor(Sensor.
				TYPE_ACCELEROMETER);

		// get the window width and height to display buttons
		// according to device screen size
		DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		mScreenHeight = displaymetrics.heightPixels;
		mScreenWidth = displaymetrics.widthPixels;
		// I need to get the dimensions of this drawable to set margins
		// for the ImageView that is used to take pictures
		Drawable mButtonDrawable = this.getResources().
		getDrawable(R.drawable.camera);

		mTakePicture = (ImageView) findViewById(R.id.startcamerapreview);

		// setting where I will draw the ImageView for taking pictures
		LayoutParams lp = new LayoutParams(mTakePicture.getLayoutParams());
		lp.setMargins((int)((double)mScreenWidth*.85),
				(int)((double)mScreenHeight*.70) ,
				(int)((double)mScreenWidth*.85)+mButtonDrawable.
				getMinimumWidth(),
				(int)((double)mScreenHeight*.70)+mButtonDrawable.
				getMinimumHeight());
		mTakePicture.setLayoutParams(lp);
		// rec is used for onInterceptTouchEvent. I pass this from the
		// highest to lowest layer so that when this area of the screen
		// is pressed, it ignores the TouchView events and passes it to
		// this activity so that the button can be pressed.
		rec.set((int)((double)mScreenWidth*.85),
				(int)((double)mScreenHeight*.10) ,
				(int)((double)mScreenWidth*.85)+mButtonDrawable.getMinimumWidth(),
				(int)((double)mScreenHeight*.70)+mButtonDrawable.getMinimumHeight());
		mButtonDrawable = null;
		mTakePicture.setClickable(true);
		mTakePicture.setOnClickListener(flashListener);
		// get our Views from the XML layout
		mPreview = (Preview) findViewById(R.id.preview);
		mView = (TouchView) findViewById(R.id.left_top_view);
		mView.setRec(rec);

	}

	// this is the autofocus call back
	private AutoFocusCallback myAutoFocusCallback = new AutoFocusCallback(){

		public void onAutoFocus(boolean autoFocusSuccess, Camera arg1) {
			//Wait.oneSec();
			mAutoFocus = true;
		}};
</pre>
<p>The onCreate method sets the accelerometer so it can be used to do autofocus for the camera. It also gets the screen&#8217;s width and height so it can place the imageviews in the same spot for the different screen sizes that android devices have. Then we create the autofocus method.</p>
<p>The code below has a method called getRatio(). This method is what translates from screen size to pixels so that the bounding rectangle grabs the right part of the image. </p>
<p>Below after that is the onClick listener previewListener( below the flashListener). This is the method that takes the picture. It opens a thread to take and save the picture. Notice that it calls Preview.getPic(), which we talked about before. This is the heart of saving the image in the sd card using savePhoto() which has not been explained or showed yet.</p>
<pre class="brush: java; title: ; notranslate">
		// with this I get the ratio between screen size and pixels
		// of the image so I can capture only the rectangular area of the
		// image and save it.
		public Double[] getRatio(){
			Size s = mPreview.getCameraParameters().getPreviewSize();
			double heightRatio = (double)s.height/(double)mScreenHeight;
			double widthRatio = (double)s.width/(double)mScreenWidth;
			Double[] ratio = {heightRatio,widthRatio};
			return ratio;
		}

		// I am not using this in this example, but its there if you want
		// to turn on and off the flash.
		private OnClickListener flashListener = new OnClickListener(){

			@Override
			public void onClick(View v) {
				if (mFlashBoolean){
					mPreview.setFlash(false);
				}
				else{
					mPreview.setFlash(true);
				}
				mFlashBoolean = !mFlashBoolean;
			}

		};

		// This method takes the preview image, grabs the rectangular
		// part of the image selected by the bounding box and saves it.
		// A thread is needed to save the picture so not to hold the UI thread.
		private OnClickListener previewListener = new OnClickListener() {

			@Override
			public void onClick(View v) {
				//if (mAutoFocus){
					mAutoFocus = false;
					mPreview.setFlash(false);
					//mPreview.setCameraFocus(myAutoFocusCallback);
					Wait.oneSec();
					Log.i(&quot;TESTESTEST&quot;,&quot;Taking picture&quot;);
					Thread tGetPic = new Thread( new Runnable() {
						public void run() {
							Double[] ratio = getRatio();
							int left = (int) (ratio[1]*(double)mView.getmLeftTopPosX());
							// 0 is height
							int top = (int) (ratio[0]*(double)mView.getmLeftTopPosY());

							int right = (int)(ratio[1]*(double)mView.getmRightBottomPosX());

							int bottom = (int)(ratio[0]*(double)mView.getmRightBottomPosY());

							savePhoto(mPreview.getPic(left,top,right,bottom));
							mAutoFocus = true;
						}
					});
					tGetPic.start();
				//}
				boolean pressed = false;
				if (!mTakePicture.isPressed()){
					pressed = true;
				}
			}
		};

		// just to close the app and release resources.
		@Override
		public boolean onKeyDown(int keyCode, KeyEvent event) {

			if (keyCode == KeyEvent.KEYCODE_BACK){
				finish();
			}
			return super.onKeyDown(keyCode, event);
		}

		private boolean savePhoto(Bitmap bm) {
			FileOutputStream image = null;
			try {
				image = new FileOutputStream(mLocation);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			bm.compress(CompressFormat.JPEG, 100, image);
			if (bm != null) {
				int h = bm.getHeight();
				int w = bm.getWidth();
				//Log.i(TAG, &quot;savePhoto(): Bitmap WxH is &quot; + w + &quot;x&quot; + h);
			} else {
				//Log.i(TAG, &quot;savePhoto(): Bitmap is null..&quot;);
				return false;
			}
			return true;
		}
</pre>
<p>Below is the onInterceptTouch(). This is what allows the take picture button to be pressed and the TouchView onTouchEvents to be ignored.</p>
<pre class="brush: java; title: ; notranslate">
		public boolean onInterceptTouchEvent(MotionEvent ev) {
			final int action = ev.getAction();
			boolean intercept = false;
			switch (action) {
			case MotionEvent.ACTION_UP:
				break;
			case MotionEvent.ACTION_DOWN:
				float x = ev.getX();
				float y = ev.getY();
				// here we intercept the button press and give it to this
				// activity so the button press can happen and we can take
				// a picture.
				if ((x &gt;= rec.left) &amp;&amp; (x &lt;= rec.right) &amp;&amp; (y&gt;=rec.top) &amp;&amp; (y&lt;=rec.bottom)){
					intercept = true;
				}
				break;
			}
			return intercept;
		}
</pre>
<pre class="brush: java; title: ; notranslate">
		// mainly used for autofocus to happen when the user takes a picture
		// I also use it to redraw the canvas using the invalidate() method
		// when I need to redraw things.
		public void onSensorChanged(SensorEvent event) {

			if (mInvalidate == true){
				mView.invalidate();
				mInvalidate = false;
			}
			float x = event.values[0];
			float y = event.values[1];
			float z = event.values[2];
			if (!mInitialized){
				mLastX = x;
				mLastY = y;
				mLastZ = z;
				mInitialized = true;
			}
			float deltaX  = Math.abs(mLastX - x);
			float deltaY = Math.abs(mLastY - y);
			float deltaZ = Math.abs(mLastZ - z);

			if (deltaX &gt; .5 &amp;&amp; mAutoFocus){ //AUTOFOCUS (while it is not autofocusing)
				mAutoFocus = false;
				//mPreview.setCameraFocus(myAutoFocusCallback);
			}
			if (deltaY &gt; .5 &amp;&amp; mAutoFocus){ //AUTOFOCUS (while it is not autofocusing)
				mAutoFocus = false;
				//mPreview.setCameraFocus(myAutoFocusCallback);
			}
			if (deltaZ &gt; .5 &amp;&amp; mAutoFocus){ //AUTOFOCUS (while it is not autofocusing) */
				mAutoFocus = false;
				//mPreview.setCameraFocus(myAutoFocusCallback);
			}

			mLastX = x;
			mLastY = y;
			mLastZ = z;

		}

		// extra overrides to better understand app lifecycle and assist debugging
		@Override
		protected void onDestroy() {
			super.onDestroy();
			//Log.i(TAG, &quot;onDestroy()&quot;);
		}

		@Override
		protected void onPause() {
			super.onPause();
			//Log.i(TAG, &quot;onPause()&quot;);
			mSensorManager.unregisterListener(this);
		}

		@Override
		protected void onResume() {
			super.onResume();
			mSensorManager.registerListener(this, mAccel, SensorManager.SENSOR_DELAY_UI);
			//Log.i(TAG, &quot;onResume()&quot;);
		}

		@Override
		protected void onRestart() {
			super.onRestart();
			//Log.i(TAG, &quot;onRestart()&quot;);
		}

		@Override
		protected void onStop() {
			super.onStop();
			//Log.i(TAG, &quot;onStop()&quot;);
		}

		@Override
		protected void onStart() {
			super.onStart();
			//Log.i(TAG, &quot;onStart()&quot;);
		}

		public void onAccuracyChanged(Sensor sensor, int accuracy) {
			// TODO Auto-generated method stub

		}
</pre>
<p>The onSensorChanged takes care of not only causing the autofocus but also invalidating (calling the onDraw()) the TouchView when a boolean is set to true.</p>
<p>Finally we have the Activity lifecycle methods that release resources (camera and sensors) onPause() and registers them onStart(). That is it guys. Try it out and make some cool apps.</p>
]]></content:encoded>
			<wfw:commentRss>http://adblogcat.com/a-camera-preview-with-a-bounding-box-like-google-goggles/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Placing a call</title>
		<link>http://adblogcat.com/making-a-call/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=making-a-call</link>
		<comments>http://adblogcat.com/making-a-call/#comments</comments>
		<pubDate>Wed, 08 Feb 2012 23:00:11 +0000</pubDate>
		<dc:creator>guitarbaka</dc:creator>
				<category><![CDATA[Telephone]]></category>
		<category><![CDATA[android make call]]></category>
		<category><![CDATA[android place call]]></category>
		<category><![CDATA[call]]></category>
		<category><![CDATA[make call]]></category>
		<category><![CDATA[place call]]></category>

		<guid isPermaLink="false">http://adblogcat.com/?p=165</guid>
		<description><![CDATA[This article describes how to make an application to make calls in Android. Open your manifest.xml and add the following permissions: CALL_PRIVILEGED is optional if you want to call Emergency numbers directly without user intervention (like 911). Create a class &#8230; <a href="http://adblogcat.com/making-a-call/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="tall" count="1" href="http://adblogcat.com/making-a-call/"></g:plusone></div><p id="top" />This article describes how to make an application to make calls in Android.<br />
<span id="more-165"></span><br />
Open your manifest.xml and add the following permissions:</p>
<pre class="brush: java; title: ; notranslate">
&lt;uses-permission android:name=&quot;android.permission.CALL_PHONE&quot; /&gt;
&lt;uses-permission android:name=&quot;android.permission.CALL_PRIVILEGED&quot; /&gt;
</pre>
<p>CALL_PRIVILEGED is optional if you want to call Emergency numbers directly without user intervention (like 911).<br />
Create a class CallPhoneTest that extends Activity. This code is extremely simple, just create an intent with the ACTION_CALL and start the Activity:</p>
<pre class="brush: java; title: ; notranslate">
public class CallPhoneTest extends Activity {

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.call_phone);
		call();
	}

	private void call() {
		try {
			Intent callIntent = new Intent(Intent.ACTION_CALL);
			callIntent.setData(Uri.parse(&quot;tel:911&quot;));
			startActivity(callIntent);
		} catch (ActivityNotFoundException activityException) {
			Toast toast = Toast.makeText(this, &quot;Cannot place a call&quot;,
					Toast.LENGTH_SHORT);
			toast.show();
		}
	}
}

And that is it!
</pre>
]]></content:encoded>
			<wfw:commentRss>http://adblogcat.com/making-a-call/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Parse JSON data from a web server and display on ListView</title>
		<link>http://adblogcat.com/parse-json-data-from-a-web-server-and-display-on-listview/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=parse-json-data-from-a-web-server-and-display-on-listview</link>
		<comments>http://adblogcat.com/parse-json-data-from-a-web-server-and-display-on-listview/#comments</comments>
		<pubDate>Wed, 08 Feb 2012 22:16:54 +0000</pubDate>
		<dc:creator>guitarbaka</dc:creator>
				<category><![CDATA[HTTP]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Network]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[android parse json]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[network]]></category>
		<category><![CDATA[parse json]]></category>

		<guid isPermaLink="false">http://adblogcat.com/?p=143</guid>
		<description><![CDATA[This article describes how to create an HTTP connection from an android device to a web server, grab JSON data, parse and display it on a ListView. The ListView is custom thus allowing me to add other Views along the &#8230; <a href="http://adblogcat.com/parse-json-data-from-a-web-server-and-display-on-listview/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="tall" count="1" href="http://adblogcat.com/parse-json-data-from-a-web-server-and-display-on-listview/"></g:plusone></div><p id="top" />This article describes how to create an HTTP connection from an android device to a web server, grab JSON data, parse and display it on a ListView. The ListView is custom thus allowing me to add other Views along the ListView. This was written using Android 2.1 APIs.</p>
<p><span id="more-143"></span><br />
<script type="text/javascript">// <![CDATA[
google_ad_client = "ca-pub-1316223412202970";
/* 300_250_medium_rectangle_custom */
google_ad_slot = "1912768919";
google_ad_width = 300;
google_ad_height = 250;
// ]]&gt;</script><br />
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js">// <![CDATA[
// ]]&gt;</script></p>
<p>Open your manifest.xml and add the following permissions outside of the tag:</p>
<pre class="brush: java; title: ; notranslate">
&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;
</pre>
<p>Open the main.xml file and add a ListView</p>
<pre class="brush: java; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
	android:orientation=&quot;vertical&quot; android:layout_width=&quot;fill_parent&quot;
	android:layout_height=&quot;fill_parent&quot;&gt;
	&lt;ListView android:id=&quot;@android:id/list&quot; android:layout_width=&quot;fill_parent&quot;
		android:layout_height=&quot;wrap_content&quot; /&gt;
&lt;/LinearLayout&gt;
</pre>
<p>Notice here I am using</p>
<pre class="brush: java; title: ; notranslate">
android:id/list
</pre>
<p>for the ListView. Why? Most people just implement the ListActivity with the custom layout simple_list_item_1 or any of the layouts that come with android. The problem is, when people want to add over Views (Buttons, TextView, etc) they cannot because they cannot set their main.xml as the contentView, so here I have done it differently.</p>
<p>Now to the code. Create a class JSONParser that extends ListActivity. The first thing we will do is add an ArrayAdapter that uses android&#8217;s simple_list_item_1 and uses an internal method populate() to give it the ArrayList.</p>
<pre class="brush: java; title: ; notranslate">
public class JSONParser extends ListActivity {

	/** Called when the activity is first created. */
	@SuppressWarnings(&quot;unchecked&quot;)
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		setListAdapter(new ArrayAdapter(
				this,android.R.layout.simple_list_item_1,
				this.populate()));
	}
</pre>
<p>Now the JSON parsing part. Create the function populate(). Inside create an HttpURLConnection with the URL that contains the json objects.</p>
<pre class="brush: java; title: ; notranslate">
	private ArrayList&lt;String&gt; populate() {
		ArrayList&lt;String&gt; items = new ArrayList&lt;String&gt;();

		try {
			URL url = new URL
			(&quot;http://SOMETHING.json&quot;);
			HttpURLConnection urlConnection =
				(HttpURLConnection) url.openConnection();
			urlConnection.setRequestMethod(&quot;GET&quot;);
			urlConnection.connect();
                        // gets the server json data
			BufferedReader bufferedReader =
				new BufferedReader(new InputStreamReader(
						urlConnection.getInputStream()));
</pre>
<p>Finally, inside the same function, create a JSONArray and for the length of each JSONArray, get the JSONObject add the items by the TAG (in this case: text).</p>
<pre class="brush: java; title: ; notranslate">

			String next;
			while ((next = bufferedReader.readLine()) != null){
				JSONArray ja = new JSONArray(next);

				for (int i = 0; i &lt; ja.length(); i++) {
					JSONObject jo = (JSONObject) ja.get(i);
					items.add(jo.getString(&quot;text&quot;));
				}
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return items;
	}
}
</pre>
<h1>Want to learn more?</h1>
<p><strong>Check out this article on <a href="http://adblogcat.com/connect-mysql-remote-server-php/" title="Connect to MYSQL remote server database using PHP and display ListView">how to connect to a remove server MYSQL database using PHP and display the results in a ListView</a></strong></p>
]]></content:encoded>
			<wfw:commentRss>http://adblogcat.com/parse-json-data-from-a-web-server-and-display-on-listview/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Camera API &#8211; Simple way to take pictures and save them on SD card</title>
		<link>http://adblogcat.com/camera-api-simple-way-to-take-pictures-and-save-them-on-sd-card/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=camera-api-simple-way-to-take-pictures-and-save-them-on-sd-card</link>
		<comments>http://adblogcat.com/camera-api-simple-way-to-take-pictures-and-save-them-on-sd-card/#comments</comments>
		<pubDate>Wed, 08 Feb 2012 19:18:54 +0000</pubDate>
		<dc:creator>guitarbaka</dc:creator>
				<category><![CDATA[Camera]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[camera]]></category>
		<category><![CDATA[camera api]]></category>
		<category><![CDATA[save sd card]]></category>
		<category><![CDATA[simple]]></category>

		<guid isPermaLink="false">http://adblogcat.com/?p=101</guid>
		<description><![CDATA[This article describes a simple way to take pictures using Android&#8217;s built in classes and save them to the SD card. It also shows how to display the picture on the screen. All of this in less than 40 lines &#8230; <a href="http://adblogcat.com/camera-api-simple-way-to-take-pictures-and-save-them-on-sd-card/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="tall" count="1" href="http://adblogcat.com/camera-api-simple-way-to-take-pictures-and-save-them-on-sd-card/"></g:plusone></div><p id="top" />This article describes a simple way to take pictures using Android&#8217;s built in classes and save them to the SD card. It also shows how to display the picture on the screen. All of this in less than 40 lines of code. This was written using Android 2.1 APIs.<br />
<span id="more-101"></span><br />
Open your manifest.xml and add the following permissions outside of the tag:</p>
<pre class="brush: java; title: ; notranslate">
&lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot; /&gt;
&lt;uses-permission android:name=&quot;android.permission.CAMERA&quot; /&gt;
</pre>
<p>Now open the main.xml file and create an ImageView. This will be used to display the picture.</p>
<pre class="brush: java; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
	android:orientation=&quot;vertical&quot; android:layout_width=&quot;fill_parent&quot;
	android:layout_height=&quot;fill_parent&quot;&gt;
	&lt;TextView android:layout_width=&quot;wrap_content&quot;
		android:layout_height=&quot;wrap_content&quot; android:text=&quot;Camera Test&quot; /&gt;
	&lt;ImageView android:id=&quot;@+id/camera_image&quot;
		android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; /&gt;
&lt;/LinearLayout&gt;
</pre>
<p>Now for the code:</p>
<pre class="brush: java; title: ; notranslate">
package com.camera.test;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.widget.ImageView;

public class CameraTest extends Activity {

	private static final int CAMERA_PIC_REQUEST = 1111;
	private ImageView mImage;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.camera_test);

		mImage = (ImageView) findViewById(R.id.camera_image);
		//1
		Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
		startActivityForResult(intent, CAMERA_PIC_REQUEST);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == CAMERA_PIC_REQUEST) {
			//2
			Bitmap thumbnail = (Bitmap) data.getExtras().get(&quot;data&quot;);
			mImage.setImageBitmap(thumbnail);
			//3
			ByteArrayOutputStream bytes = new ByteArrayOutputStream();
			thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
			//4
			File file = new File(Environment.getExternalStorageDirectory()+File.separator + &quot;image.jpg&quot;);
			try {
				file.createNewFile();
				FileOutputStream fo = new FileOutputStream(file);
				//5
				fo.write(bytes.toByteArray());
				fo.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
</pre>
<p>1. Using android.provider.MediaStore.ACTION_IMAGE_CAPTURE, we can launch an intent to take the picture without having to specify any Camera APIs.<br />
2. From the data extras we get back from ActivityonResult, we can get the image Bitmap and put it in our ImageView.<br />
3. The image Bitmap from number 2 gets compressed as a jpeg for saving and gets stored into a ByteArrayOutputStream.<br />
4. Create a new file that will be stored in the SD card with a name; here &#8220;image.jpg&#8221;.<br />
5. Write the Bitmap to the file by writing the BiteArrayOutputStream to the file using a FileOutputStream.</p>
]]></content:encoded>
			<wfw:commentRss>http://adblogcat.com/camera-api-simple-way-to-take-pictures-and-save-them-on-sd-card/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
