Payday Loan Payday Loan

Archive for the ‘Algorithms’ Category

Hi,
Today i want to show you something very interesting in Android. I see that on the internet there are no tutorials for helping you to implement from A – Z your own listener.
Let me give an use case.
So you have two classes. One extends Activity in which you have a Button, and in the second one you need to listen to events, in our case you will listen to the event that a click was done in some Activity.
You will need to implement an interface and a singleton class like this:

 
public interface EventListener
{
	public void onEventHappened();
}

This interface must be in a separate file (Interface)called EventListener
Now the class:

 
public class MyEvent
{
	private EventListener listener;
	private static MyEvent instance;
 
	private MyEvent(){
 
	}
	public static MyEvent getInsance(){
		if (instance == null)
			instance = new MyEvent();
		return instance;
	}
	public void setEventListener(EventListener listen)
	{		
		listener = listen;
	}
 
	public void eventHappened()
	{		
		if (listener != null)
		{
			listener.onEventHappened();
		}
	}
}

Now that you have those two classes copied in your project let me tell you how to use them.
So in the Activity where you have the Button in onClick method you put the code:

MyEvent.getInstance().eventHappened();

Now let s say that in any of your other classes you want to be notified about this event.
You will put in your other class the following code:

MyEvent.getInsance().setEventListener(new EventListener()
		{
 
			@Override
			public void onEventHappened()
			{
                            //here is your code that will happen when the button from the other Activity was pressed
                        }
                 });
||||| 0 I Like It! |||||

The following regex expression will help you to determine if there is a valid e-mail address or not in your edit text.

public static boolean isValid(String email) {
 
    String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
    CharSequence inputStr = email;
    Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(inputStr);
    if (matcher.matches()) {
        return true;
    }
    else{
    return false;
    }
}
||||| 0 I Like It! |||||

Hi,
Today i want to show you how you can serialize or deserialize an Object. I will take like example a String object, but there can be any type of Object.
To serialize an object means to make it a binary, and to deserialize it, means to make it from binary to the Object.
So let’s start.
This is the method for serializing a generic Object.

public class SerializeClass {
 public static byte[] serializeObject(Object o) { 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
 
    try { 
      ObjectOutput out = new ObjectOutputStream(baos); 
      out.writeObject(o); 
      out.close(); 
 
      // Get the bytes of the serialized object 
      byte[] buffer = baos.toByteArray(); 
 
      return buffer; 
    } catch(IOException ioe) { 
 
      return null; 
    } 
 }
 public static Object deserializeObject(byte[] b) { 
    try { 
      ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(b)); 
      Object object = in.readObject(); 
      in.close(); 
 
      return object; 
    } catch(ClassNotFoundException cnfe) { 
      Log.e("deserializeObject", "class not found error", cnfe); 
 
      return null; 
    } catch(IOException ioe) { 
      Log.e("deserializeObject", "io error", ioe); 
 
      return null; 
    } 
  } 
}

To call this methods you will do like this:
Your class must implement Serializable for this to work

public class MyClass implements Serializable {
 String text;
 
MyClass myClass = new MyClass();
byte[] binaryObject = SerializeClass.serializeObject(myClass);
MyClass deserializedMyClass = SerializeClass.deserializeObject(binaryObject);
||||| 1 I Like It! |||||

How to encrypt password in Android

There is a function that will encrypt a string in a md5 password in android.
If you need to send an encrypted password over a http post, then this is a secure way.
This is the function to call:

public static final String md5(final String s) {
	    try {
	        // Create MD5 Hash
	        MessageDigest digest = java.security.MessageDigest
	                .getInstance("MD5");
	        digest.update(s.getBytes());
	        byte messageDigest[] = digest.digest();
 
	        // Create Hex String
	        StringBuffer hexString = new StringBuffer();
	        for (int i = 0; i < messageDigest.length; i++) {
	            String h = Integer.toHexString(0xFF & messageDigest[i]);
	            while (h.length() < 2)
	                h = "0" + h;
	            hexString.append(h);
	        }
	        return hexString.toString();
 
	    } catch (NoSuchAlgorithmException e) {
	        e.printStackTrace();
	    }
	    return "";
	}

To call this function:

String myPassword="password";
String encryptedPassword=md5(myPassword);
||||| 0 I Like It! |||||

In this tutorial i want to show you some common usefull convertings.
Convert Drawable to bitmap:

Bitmap icon= BitmapFactory.decodeResource(context.getResources(),
                    R.drawable.icon_resource);

Convert Bitmap to drawable:

Drawable d =new BitmapDrawable(bitmap);

Convert imageview to bitmap:

ImageView image=new ImageView(context);
 Bitmap viewBitmap = Bitmap.createBitmap(i.getWidth(),i.getHeight(),Bitmap.Config.ARGB_8888);//i is imageview which u want to convert in bitmap
Canvas canvas = new Canvas(viewBitmap);
 
image.draw(canvas);

Convert List to String[]:

 static String[] convert(List<String[]> from) {
        ArrayList<String> list = new ArrayList<String>();
        for (String[] strings : from) {
            Collections.addAll(list, strings);
        }
        return list.toArray(new String[list.size()]);
    }

Example of using the function:

  public static void main(String[] args) {
        List<String[]> list = new ArrayList<String[]>();
        list.add(new String[] { "a", "b" });
        list.add(new String[] { "c", "d", "e" });
        list.add(new String[] { "f", "g" });
        String[] converted = convert(list);
        System.out.print(converted.toString());
    }

Convert seconds to date time string:

SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMMM d, yyyy HH:mm");
String dateString = formatter.format(new Date(seconds * 1000L));
||||| 0 I Like It! |||||

Hi, I was need to implement in my job something that simulate a shuffle.
The best random shuffle simulator is the algorithm Fisher-Yates.
Here is the implementation:

import java.util.Random;
 
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
 
public class Main extends Activity {
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final TextView text=(TextView)findViewById(R.id.textView1);
 
        Button start=(Button)findViewById(R.id.button1);
        start.setOnClickListener(new OnClickListener(){
 
			@Override
			public void onClick(View v) {
//for example we want to shuffle letters from the word "Android" and to display the result in a textview
//but this can be used to shuffle anything...like card games or something else.
//function shuffling will return us a string that will be shuffled.
String new_string = shuffling("Android");
text.setText(new_string);
			}
 
        });
    }
 
 static String shuffling(String s) {
    char[] y = s.toCharArray();
    final int n = y.length;
    Random rand = new Random();
    for (int i=n-1;i>=0;i--) {
        int j=rand.nextInt(i + 1);
        permutations(y, i, j);
    }
    return new String(x);
}
 static void permutations(char[] a, int i, int j) {
    char text = a[i];
    a[i]= a[j];
    a[j]= text;
}
 
}
||||| 3 I Like It! |||||

Search

Popular

Sponsors