Saturday, June 29, 2013

View Pager In Android

Hi Guys!


Today I am going to share the code to make a view pager in android. In the new API- 17 gallery is debricated  now. So android developer suggest that please use the view pager or horizontal scroll veiw in place of Gallery.

Viewpager  is  the best way to switching among view. It provide a way to swipe views from left to right and right to left. Viewpager provide strong way to swipe any views but here i have taken ImageView to swipe left and right.
Here the the link, you can see the ViewPager in android API.

Add the support library while you are creating project because Viewpager does not support in lower android version.

miain.xml






PageIndicatorActivity.java

package com.sunil.viewpager;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Menu;

public class PageIndicatorActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ViewPagerAdapter adapter = new ViewPagerAdapter(this, imageArra);
ViewPager myPager = (ViewPager) findViewById(R.id.myfivepanelpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
}

private int imageArra[] = { R.drawable.sunn, R.drawable.sunnew,
R.drawable.sunn, R.drawable.sunnew,
R.drawable.sunn, R.drawable.sunnew,
R.drawable.sunn, R.drawable.sunnew, };


}

ViewPagerAdapter.java

package com.sunil.viewpager;

import android.app.Activity;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

public class ViewPagerAdapter extends PagerAdapter {

Activity activity;
int imageArray[];

public ViewPagerAdapter(Activity act, int[] imgArra) {
imageArray = imgArra;
activity = act;
}

public int getCount() {
return imageArray.length;
}

public Object instantiateItem(View collection, int position) {
ImageView view = new ImageView(activity);
view.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
view.setScaleType(ScaleType.FIT_XY);
view.setBackgroundResource(imageArray[position]);
((ViewPager) collection).addView(view, 0);
return view;
}

@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}

@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}

@Override
public Parcelable saveState() {
return null;
}
}



Cheers Guys!

Monday, June 17, 2013

Web browser by Action View

Hi Guys!

Today I am going to share the code for open web browser by action view in android.
In this article we will create an application which will open a user input website in a web browser. In order to open a web browser, we will create an intent object with ACTION_VIEW as action and data with �http� in the url. Since http request is invoked by the external browser, no explicit permission is needed for this application.

activity_main.xml






MainActivity.java

package com.sunil.browserview;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity implements OnClickListener{

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

Button btn = (Button) findViewById(R.id.btn_browse);
btn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
EditText txt = (EditText) findViewById(R.id.te_url);

Intent intent = new Intent("android.intent.action.VIEW");

Uri data = Uri.parse("http://"+txt.getText().toString());

intent.setData(data);

startActivity(intent);

}
}


Dial Number In Android Phone

Hi Guys!
Today I am sharing the code for dial a number to call any guys from android device.
In this article we will create an application which can call a telephone number directly from the application. In order to call a number we will make use the standard action called ACTION_CALL. An application can  call a number directly if  and only if  the necessary permission is explicitly granted. For this we need to provide CALL_PHONE permission to the application.

Main.xml






MainActivity.java

package com.sunil.call;


import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity implements OnClickListener{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button btn = (Button) findViewById(R.id.btnCall);
btn.setOnClickListener(this);

}

@Override
public void onClick(View v) {

EditText telNo = (EditText) findViewById(R.id.telNo);
String strTelNo = telNo.getText().toString();
Intent intent = new Intent("android.intent.action.CALL");

Uri data = Uri.parse("tel:"+ strTelNo );

intent.setData(data);
startActivity(intent);

}
}

Menifest.xml



















Cheers Guys!

Phone Dialer In Android

Hi Guys!
Today i am going to share the code of Action dial in android.
Phone dialer is an activity available with Android operating system to call a number. In this article, we will create an application which invokes the dialer on a button click.  Android system provides a standard action name called �ACTION_DIAL� to invoke the dialer. We will make use this action to invoke the the dialer from our application.

Main.xml




MainActivity.java

package com.sunil.dial;

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

public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button btn = (Button) findViewById(R.id.btn);

OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("android.intent.action.DIAL");
startActivity(intent);
}
};

btn.setOnClickListener(listener);
}
}


Cheers Guys!

Monday, June 10, 2013

Download Image From Server

Hi Guys!
Today i going to share the code to download the image from server. This is a sample activity which shows how to get image files from the web and display them using the ImageView view.

main.xml





DownloadImageActivity.java

package com.sunil.download;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;

public class DownloadImageActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Bitmap bitmap = DownloadImage(
"http://www.allindiaflorist.com/imgs/arrangemen4.jpg");
ImageView img = (ImageView) findViewById(R.id.img);
img.setImageBitmap(bitmap);
}

private InputStream OpenHttpConnection(String urlString)
throws IOException
{
InputStream in = null;
int response = -1;

URL url = new URL(urlString);
URLConnection conn = url.openConnection();

if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");

try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();

response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
}
private Bitmap DownloadImage(String URL)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
}

menifest.xml














Cheers guys!

Sunday, June 9, 2013

PDF Generate in Android

Hi guys!
Today I am going to share pdf generate in Android tutorial. This tutorial will help you generate your own PDF file in Android. Sometimes, you need to create certain applications where in you want to output the details in the form of a PDF file so that it could printed or used in some other way.

In order to generate PDF we are going to use an external library called Droidtext which is used for PDF creation. It comes with a desktop version and an Android version, the differences between the two can be found over here. For this tutorial, I will be using the Android version.

Add Droidtext .jar file to Android project inside the libs folder and make a java build path.

activity_main.xml






MainActivity.java

package com.example;

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

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.Image;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.PdfWriter;

public class MainActivity extends Activity {


private Button b;

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

b= (Button)findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
createPDF();

}
});

}


public void createPDF()
{
Document doc = new Document();


try {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/droidText";

File dir = new File(path);
if(!dir.exists())
dir.mkdirs();

Log.d("PDFCreator", "PDF Path: " + path);


File file = new File(dir, "sample.pdf");
FileOutputStream fOut = new FileOutputStream(file);

PdfWriter.getInstance(doc, fOut);

//open the document
doc.open();


Paragraph p1 = new Paragraph("Hi! I am generating my first PDF using DroidText");
Font paraFont= new Font(Font.COURIER);
p1.setAlignment(Paragraph.ALIGN_CENTER);
p1.setFont(paraFont);

//add paragraph to document
doc.add(p1);

Paragraph p2 = new Paragraph("This is an example of a simple paragraph");
Font paraFont2= new Font(Font.COURIER,14.0f,Color.GREEN);
p2.setAlignment(Paragraph.ALIGN_CENTER);
p2.setFont(paraFont2);

doc.add(p2);

ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getBaseContext().getResources(), R.drawable.android);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.setAlignment(Image.MIDDLE);

//add image to document
doc.add(myImg);

//set footer
Phrase footerText = new Phrase("This is an example of a footer");
HeaderFooter pdfFooter = new HeaderFooter(footerText, false);
doc.setFooter(pdfFooter);



} catch (DocumentException de) {
Log.e("PDFCreator", "DocumentException:" + de);
} catch (IOException e) {
Log.e("PDFCreator", "ioException:" + e);
}
finally
{
doc.close();
}

}
}

Menifest.xml


















Cheers Guys!

Saturday, June 1, 2013

Password MD5 and SHA1 in Android

In this tutorial, I will demonstrate how to go about hashing a password using SHA1 and MD5 hashing techniques!

Security plays an important role especially in applications where in you need to connect to the Internet. Hashes are useful in such cases since they help to ensure that the transmitted messages are not altered by any means. In general, a hash value or a hash, also known as message digest is a number generated from a string of text. Android provides us with the MessageDigest class that enables developers to create and use hashes while comparing user credentials.

MessageDigest class
As mentioned in the Android docs, the class uses a one-way hash function to turn an arbitrary number of bytes into a fixed-length byte sequence. The original arbitrary-length sequence is the message, and the fixed-length byte sequence is the digest or message digest.

1. SHA1
 
SHA stands for secure hashing algorithm. SHA-1 produces a 160-bit message digest and is considered to be more secure than MD5. However, when compared to SHA256 it is not that secure.

2. MD5
 
It is widely used cryptographic hash function that produces a 128 bit (16 byte) hash value. It is represented in the form of a 32 digit hexadecimal number and cannot not decrypted. The downside of the algorithm is the fact that it has been broken as mentioned over here.

Now, let�s create an Android application project to implement SHA-1 and MD5.

activity_main.xml














strings.xml



AndroidHashDemo
Settings
Android Hash Demo!
enter your username!
enter your password!


MainActivity.java

package com.sunil.password;

import java.io.IOException;
import android.util.Base64;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import com.example.R;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

private TextView result;
private Button computeSha,computeMD5;
private EditText userName, passWord;
private String username,passwd;
private String SHAHash;
public static int NO_OPTIONS=0;

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

userName=(EditText)findViewById(R.id.userName);
passWord=(EditText)findViewById(R.id.passWord);

computeSha=(Button)findViewById(R.id.btn1);
computeMD5=(Button)findViewById(R.id.btn2);

result= (TextView)findViewById(R.id.textView2);

//get username and password entered
username= userName.getText().toString();
passwd= passWord.getText().toString();

//check if username or passwd is not null

if( (username != null && username.equals("") ) || (passwd !=null && passwd.equals("")) )
{
computeSha.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
//call method to compute SHA hash
computeSHAHash(passwd);
}
});

computeMD5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
//call method to compute SHA hash
computeMD5Hash(passwd);
}
});

}
else
{
Toast.makeText(getApplicationContext(), "Enter your credentials..", Toast.LENGTH_LONG).show();
}

} //end onCreate()

private static String convertToHex(byte[] data) throws java.io.IOException
{
StringBuffer sb = new StringBuffer();
String hex=null;
hex=Base64.encodeToString(data, 0, data.length, NO_OPTIONS);
sb.append(hex);
return sb.toString();
}


public void computeSHAHash(String password)
{
MessageDigest mdSha1 = null;
try
{
mdSha1 = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e1) {
Log.e("myapp", "Error initializing SHA1 message digest");
}
try {
mdSha1.update(password.getBytes("ASCII"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] data = mdSha1.digest();
try {
SHAHash=convertToHex(data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

result.setText("SHA-1 hash generated is: " + " " + SHAHash);
}


public void computeMD5Hash(String password)
{

try {
// Create MD5 Hash
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(password.getBytes());
byte messageDigest[] = digest.digest();

StringBuffer MD5Hash = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++)
{
String h = Integer.toHexString(0xFF & messageDigest[i]);
while (h.length() < 2)
h = "0" + h;
MD5Hash.append(h);
}

result.setText("MD5 hash generated is: " + " " + MD5Hash);

}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}

}
}



Cheers guys!

Animation Fade-In/Out

Hello Guys!
It�s difficult to find time these days. However, I always try and make sure that the learning never stops! In this tutorial, I will talk about creating an animation using the Animation resources offered by Android.

Android includes an Animation class using which an animation can be applied to Views, Surfaces or other objects. There are basically two main types of Animations:
1. Property Animation ( android.animation)
The property animation system allows developers to animate object properties of any type, for example, int, float. One can also specify keyframes, group animations and even control the behavior of animations.
2. View Animation ( android.view.animation )
Unlike property animation, View animation is used to create simple animations such as tweened animation and frame by frame animation. Tweened animation creates an animation by performing a series of transformations on a single image where as frame by frame animation creates an animation by showing a sequence of images.
Once the above concepts are clear, we can now proceed towards creating a simple fade in/fade out animation in Android.

Expand your Project under the Package explorer window. You will find a folder named res. Inside the res folder, create a new folder named anim



res/anim/anim_fade_in.xml




res/anim/anim_fade_out.xml




activity_main.xml




MainActivity.java

package com.sunil.animation;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity
{

private ImageView image;
private Animation animFadeIn;
private Animation animFadeOut;
private Button btnFadeIn;
private Button btnFadeOut;

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

btnFadeIn = (Button)findViewById(R.id.btn_fadein);
btnFadeOut = (Button)findViewById(R.id.btn_fadeout);
image = (ImageView)findViewById(R.id.my_image);

animFadeIn = AnimationUtils.loadAnimation(this, R.anim.anim_fade_in);
btnFadeIn.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
image.startAnimation(animFadeIn);
}});

animFadeOut = AnimationUtils.loadAnimation(this, R.anim.anim_fade_out);
btnFadeOut.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
image.startAnimation(animFadeOut);
}});
}
}

Cheers Guys!

 

Copyright @ 2013 Android Developers Tipss.