Search
Sponsors
Sponsors

Archive for the ‘Source Code’ Category

Save image to media library

Thursday, August 25th, 2011

 

Uri saveMediaEntry(String imagePath,String title,String description,long dateTaken,int orientation,Location loc) {
    ContentValues v = new ContentValues();
    v.put(Images.Media.TITLE, title);
    v.put(Images.Media.DISPLAY_NAME, displayName);
    v.put(Images.Media.DESCRIPTION, description);
    v.put(Images.Media.DATE_ADDED, dateTaken);
    v.put(Images.Media.DATE_TAKEN, dateTaken);
    v.put(Images.Media.DATE_MODIFIED, dateTaken) ;
    v.put(Images.Media.MIME_TYPE, "image/jpeg");
    v.put(Images.Media.ORIENTATION, orientation);

    File f = new File(imagePath) ;
    File parent = f.getParentFile() ;
    String path = parent.toString().toLowerCase() ;
    String name = parent.getName().toLowerCase() ;
    v.put(Images.ImageColumns.BUCKET_ID, path.hashCode());
    v.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, name);
    v.put(Images.Media.SIZE,f.length()) ;
    f = null ;
   
    if( targ_loc != null ) {
        v.put(Images.Media.LATITUDE, loc.getLatitude());
        v.put(Images.Media.LONGITUDE, loc.getLongitude());
    }
    v.put("_data",imagePath) ;
    ContentResolver c = getContentResolver() ;
    return c.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, v);
}

Handling shake events

Thursday, August 25th, 2011

 

package com.gedankentank.android.sensor;

import java.util.List;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;

public class AccelerometerListener implements SensorEventListener {
   
    private SensorManager sensorManager;
    private List<Sensor> sensors;
    private Sensor sensor;
    private long lastUpdate = -1;
    private long currentTime = -1;
   
    private float last_x, last_y, last_z;
    private float current_x, current_y, current_z, currenForce;
    private static final int FORCE_THRESHOLD = 900;
    private final int DATA_X = SensorManager.DATA_X;
    private final int DATA_Y = SensorManager.DATA_Y;
    private final int DATA_Z = SensorManager.DATA_Z;
   
    public AccelerometerListener(Activity parent) {
        SensorManager sensorService = (SensorManager) parent.getSystemService(Context.SENSOR_SERVICE);
        this.sensorManager = sensorManager;
        this.subscriber = subscriber;
        this.sensors = sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
        if (sensors.size() > 0) {
            sensor = sensors.get(0);
        }
    }
    public void start () {
        if (sensor!=null)  {
            sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME);
        }
    }
   
    public void stop () {
        sensorManager.unregisterListener(this);
    }
   
    public void onAccuracyChanged(Sensor s, int valu) {
       
       
    }
    public void onSensorChanged(SensorEvent event) {
       
        if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER || event.values.length < 3)
              return;
       
        currentTime = System.currentTimeMillis();
       
        if ((currentTime - lastUpdate) > 100) {
            long diffTime = (currentTime - lastUpdate);
            lastUpdate = currentTime;
           
            current_x = event.values[DATA_X];
            current_y = event.values[DATA_Y];
            current_z = event.values[DATA_Z];
           
            currenForce = Math.abs(current_x+current_y+current_z - last_x - last_y - last_z) / diffTime * 10000;
           
            if (currenForce > FORCE_THRESHOLD) {
           
                // Device has been shaken now go on and do something
                // you could now inform the parent activity …
               
            }
            last_x = current_x;
            last_y = current_y;
            last_z = current_z;

        }
    }

}

Copy to clipboard

Thursday, August 25th, 2011

 

Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
                    ImageTransferable imageTrans = new ImageTransferable(bufferImage);
                    clip.setContents(imageTrans, null);

Check for leap year

Thursday, August 25th, 2011

 

public boolean isLeapYear(){
    boolean leapYear;
    int divideByFour = year % 4;
    int divideBy100 = year % 100;
    int divideBy400 = year % 400;
    if (divideBy400 == 0){
        leapYear = true;
    } else if (divideBy100 == 0){
        leapYear = false;
    } else if (divideByFour == 0){
        leapYear = true;
    } else {
        leapYear = false;
    }
    return leapYear;
}

Send email using Intent

Thursday, August 25th, 2011

 

Intent i = new Intent(Intent.ACTION_SEND); 
//i.setType("text/plain"); //use this line for testing in the emulator 
i.setType("message/rfc822") ; // use from live device
i.putExtra(Intent.EXTRA_EMAIL, new String[]{"test@gmail.com"}); 
i.putExtra(Intent.EXTRA_SUBJECT,"subject goes here"); 
i.putExtra(Intent.EXTRA_TEXT,"body goes here"); 
startActivity(Intent.createChooser(i, "Select email application."));

Keyboard input

Thursday, August 25th, 2011

 

import java.io.*;

public class ReadString {

   public static void main (String[] args) {

      //  prompt the user to enter their name
      System.out.print("Enter your name: ");

      //  open up standard input
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

      String userName = null;

      //  read the username from the command-line; need to use try/catch with the
      //  readLine() method
      try {
         userName = br.readLine();
      } catch (IOException ioe) {
         System.out.println("IO error trying to read your name!");
         System.exit(1);
      }

      System.out.println("Thanks for the name, " + userName);

   }

}  // end of ReadString class

JDBC and MySQL

Thursday, August 25th, 2011

 

import java.util.logging.Level;
import java.util.logging.Logger;

// import com.mysql.jdbc.*;
import java.sql.*;

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author sukanta
*/
public class Main {

    public static void main(String[] args) throws SQLException {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;

        con = DriverManager.getConnection("jdbc:mysql://datanase name", "username", "password");
        stmt = con.createStatement();
        ResultSet result = stmt.executeQuery("SELECT * FROM table1");
        while (result.next())
            System.out.println(result.getString(1) + " " + result.getString(2));
        result.close();
        con.close();
    }
}

Download a forex quote

Thursday, August 25th, 2011

 

import java.net.*;
import java.io.*;

public class ForexTest {
    public void getRate() {
        try {
            URL url = new URL("http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=EURUSD=X");
            URLConnection urlc = url.openConnection();

            BufferedReader reader = new BufferedReader(new InputStreamReader(urlc.getInputStream()));

            String line;
            StringBuffer sb = new StringBuffer();

            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            System.out.println(sb);

        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        ForexTest ft = new ForexTest();
        while (true) {
            ft.getRate();
            Thread.sleep(10000);
        }

    }
}

Download a web page

Thursday, August 25th, 2011

 

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
* Main.java
*
* @author www.javadb.com
*/
public class Main {
   
    /**
     * Reads a web page into a StringBuilder object
     * and prints it out to console along with the
     * size of the page.
     */
    public void getWebSite() {
       
        try {
           
            URL url = new URL("http://www.google.com");
            URLConnection urlc = url.openConnection();
           
            BufferedInputStream buffer = new BufferedInputStream(urlc.getInputStream());
           
            StringBuilder builder = new StringBuilder();
            int byteRead;
            while ((byteRead = buffer.read()) != -1)
                builder.append((char) byteRead);
           
            buffer.close();
           
            System.out.println(builder.toString());
            System.out.println("The size of the web page is " + builder.length() + " bytes.");
           
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    /**
     * Starts the program
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Main().getWebSite();
    }
}

Open a url in browser

Thursday, August 25th, 2011

 

Intent viewIntent = new Intent("android.intent.action.VIEW",Uri.parse("http://java.codentuts.com")); 
startActivity(viewIntent);

Translate