Showing posts with label Ajax. Show all posts
Showing posts with label Ajax. Show all posts

Saturday, 18 October 2014

Capturing image in Android

Hi friends let us learn how to create a camera based application in android.

Basics for capturing a image using existing camera in our mobile

You will use MediaStore.ACTION_IMAGE_CAPTURE to launch an existing camera application installed on your phone. Its syntax is given below
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
Apart from the above , there are other availaible Intents provided by MediaStore. They are listed as follows
Sr.NoIntent type and description
1ACTION_IMAGE_CAPTURE_SECURE
It returns the image captured from the camera , when the device is secured
2ACTION_VIDEO_CAPTURE
It calls the existing video application in android to capture video
3EXTRA_SCREEN_ORIENTATION
It is used to set the orientation of the screen to vertical or landscape
4EXTRA_FULL_SCREEN
It is used to control the user interface of the ViewImage
5INTENT_ACTION_VIDEO_CAMERA
This intent is used to launch the camea in the video mode
6EXTRA_SIZE_LIMIT
It is used to specify the size limit of video or image capture size
Now you will use the function startActivityForResult to launch this activity and wait for its result. Its syntax is given below
startActivityForResult(intent,0)
This method has been defined in the activity class. We are calling it from main activity. There are methods defined in the activity class that does the same job , but used when you are not calling from the activity but from somewhere else. They are listed below

Sr.NoActivity function description
1startActivityForResultIntentintent,intrequestCode,Bundleoptions
It starts an activity , but can take extra bundle of options with it
2startActivityFromChildActivitychild,Intentintent,intrequestCode
It launch the activity when your activity is child of any other activity
3startActivityFromChildActivitychild,Intentintent,intrequestCode,Bundleoptions
It work same as above , but it can take extra values in the shape of bundle with it
4startActivityFromFragmentFragmentfragment,Intentintent,intrequestCode
It launches activity from the fragment you are currently inside
5startActivityFromFragmentFragmentfragment,Intentintent,intrequestCode,Bundleoptions
It not only launches the activity from the fragment , but can take extra values with it
No matter which function you used to launch the activity , they all return the result. The result can be obtained by overriding the function onActivityResult.

Example

Here is an example that shows how to launch the exisitng camera application to capture an image and display the result in the form of bitmap
To experiment with this example , you need to run this on an actual device on which camera is supported.
StepsDescription
1You will use Eclipse IDE to create an Android application and name it as Camera under a package com.example.camera. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file to add intent code to launch the activity and result method to recieve the output.
3Modify layout XML file res/layout/activity_main.xml add any GUI component if required. Here we add only imageView and a textView.
4Modify res/values/strings.xml to define required constant values
5Run the application and choose a running android device and install the application on it and verify the results.
Following is the content of the modified main activity file src/com.example.camera/MainActivity.java.
package com.example.camera;


import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

public class MainActivity extends Activity {

ImageView imgFavorite;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      imgFavorite = (ImageView)findViewById(R.id.imageView1);
      imgFavorite.setOnClickListener(new OnClickListener() {
         @Override
         public void onClick(View v) {
            open();
         }
      });
   }
   public void open(){
      Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
      startActivityForResult(intent, 0);
   }

   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      // TODO Auto-generated method stub
      super.onActivityResult(requestCode, resultCode, data);
      Bitmap bp = (Bitmap) data.getExtras().get("data");
      imgFavorite.setImageBitmap(bp);
   }
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   }
}
Following will be the content of res/layout/activity_main.xml file:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".MainActivity"> 

   <ImageView
   android:id="@+id/imageView1"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:layout_marginLeft="34dp"
   android:layout_marginTop="36dp"
   android:contentDescription="@string/hello_world"
   android:src="@drawable/ic_launcher" />

   <TextView
   android:id="@+id/textView1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignParentTop="true"
   android:layout_alignRight="@+id/imageView1"
   android:text="@string/tap"
   android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>
Following will be the content of res/values/strings.xml to define one new constants
<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="app_name">Camera</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">Hello world!</string>
   <string name="tap">Tap the image to open the camera!!</string>
</resources>
Following is the default content of AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.camera"
   android:versionCode="1"
   android:versionName="1.0" >

   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="17" />

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
         <activity
            android:name="com.example.camera.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
               <action android:name="android.intent.action.MAIN" />

               <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
   </application>

</manifest>
Let's try to run your Camera application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Eclipse, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar.

Friday, 19 September 2014

Asynchronous file upload - PHP & AJAX

 Asynchronous file upload - PHP & AJAX

Asynchronous file uploads is quote popular feature in modern AJAX web-applications. However standard AJAX classes (XmlHttpRequest) does not have capabilities to process or send files selected with "file dialog" (input type="file"). This article contains example application (trivial file-sharing service, like rapidshare, megaupload or yousendit) which uses embedded frames (IFRAME) to upload file. While file is uploaded to hidden frame, user can still access web-page and fill "file description" field.

Compatible 

  1. Adequate versions of Opera, Firefox, Internet Explorer, Safari
  2. PHP 4.3.0 or higher
  3. PHP 5
  4. PHP option 'short_open_tag' switched on (parse errors otherwise)

How IFRAME file uploading works?


    There is a simple <form... which contains only <input type="file" ... > field. Target for this form is a hidden IFRAME (with "display: none;" CSS style) and OnChange event for the file field is set to JavaScript function which checks file extension (optional for this example, but very useful in general) and submits form.
    Special part of the script (marked FILEFRAME, see comments) saves file upload, checks for uploading errors and outputs JavaScript code to that hidden IFRAME. The javascript code uses parent.window.document object, which allows to modify parent document (visible page, which users is viewing). It sets filename value and enables submit button on the other form using getElementById method.
    The other form has 'description' text-field and hidden field 'filename'. User may fill 'description' field while file is uploading. When file uploading is finished, user press submit and "file information" page is generated (based on filename from hidden field and user's file description).

Possible drawback of this method is file garbage: files are uploaded even if user does not press submit button. You may need to write 'garbage file collector' which will delete any unused file.
This example stores all uploaded file in filesystem folder. You need to specify it at the beginning of script, see variables $upload_dir and $web_upload_dir. There is fail-checking which checks whether it is possible to write create files in upload directory.

We use following functions in this example: PHP


    move_uploaded_file - move file uploaded to web server
    fopen - open file
    fwrite - write to opened file
    fclose - close file
    str_replace - replace one substring by another
    filesize - returns file size in bytes
    filemtime - returns file modification time

source code: php


$upload_dir = "/var/www/xxx/yyy"; // Directory for file storing
                                            // filesystem path

$web_upload_dir = "/yyy"; // Directory for file storing
                          // Web-Server dir

/* upload_dir is filesystem path, something like
   /var/www/htdocs/files/upload or c:/www/files/upload

   web upload dir, is the webserver path of the same
   directory. If your upload-directory accessible under
   www.your-domain.com/files/upload/, then
   web_upload_dir is /files/upload
*/


// testing upload dir
// remove these lines if you're shure
// that your upload dir is really writable to PHP scripts$tf = $upload_dir.'/'.md5(rand()).".test";$f = @fopen($tf, "w");
if ($f == false)
    die("Fatal error! {$upload_dir} is not writable. Set 'chmod 777 {$upload_dir}'
        or something like this");fclose($f);unlink($tf);// end up upload dir testing



// FILEFRAME section of the scriptif (isset($_POST['fileframe']))
{
    $result = 'ERROR';
    $result_msg = 'No FILE field found';

    if (isset($_FILES['file']))  // file was send from browser
    {
        if ($_FILES['file']['error'] == UPLOAD_ERR_OK)  // no error
        {
            $filename = $_FILES['file']['name']; // file name
            move_uploaded_file($_FILES['file']['tmp_name'], $upload_dir.'/'.$filename);
            // main action -- move uploaded file to $upload_dir
            $result = 'OK';
        }
        elseif ($_FILES['file']['error'] == UPLOAD_ERR_INI_SIZE)
            $result_msg = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
        else
            $result_msg = 'Unknown error';

        // you may add more error checking
        // see http://www.php.net/manual/en/features.file-upload.errors.php
        // for details
    }

    // outputing trivial html with javascript code
    // (return data to document)

    // This is a PHP code outputing Javascript code.
    // Do not be so confused ;)
    echo '-';
    echo '';

    exit(); // do not go futher }// FILEFRAME section END



// just userful functions
// which 'quotes' all HTML-tags and special symbols
// from user input function safehtml($s)
{
    $s=str_replace("&", "&", $s);
    $s=str_replace("<", "<", $s);
    $s=str_replace(">", ">", $s);
    $s=str_replace("'", "'", $s);
    $s=str_replace("\"", """, $s);
    return $s;
}

if (isset($_POST['description']))
{
  
    // Let's generate file information page$html =<<{$filename} [uploaded by IFRAME Async file uploader]

{$filename}


This is a file information page for your uploaded file. Bookmark it, or send to anyone...

Date: {$date}

Size: {$size} bytes

Description:
{$description}


download file

back to file uploading

upload-log



Example by Developers Guide
END;
    // save HTML
    $f = fopen($upload_dir.'/'.$filename.'-desc.html', "w");
    fwrite($f, $html);
    fclose($f);
    $msg = "File {$filename} uploaded,
           see file information page";

    // Save to file upload-log
    $f = fopen($upload_dir."/upload-log.html", "a");
    fwrite($f, "
$msg
\n");
    fclose($f);

    // setting result message to cookie 
    setcookie('msg', $msg);
    // redirecting to the script main page
    // we're doing so, to avoid POST form reposting 
    // this method of outputting messages is called 'flash' in Ruby on Rails 
    header("Location: http://".$_SERVER['HTTP_HOST'].$PHP_SELF);
    exit();
    // redirect was send, so we're exiting now}
 // retrieving message from cookie if (isset($_COOKIE['msg']) && $_COOKIE['msg'] != '') 

    if (get_magic_quotes_gpc())
        $msg = stripslashes($_COOKIE['msg']);
    else
        $msg = $_COOKIE['msg'];

    // clearing cookie, we're not going to display same message several times
    setcookie('msg', '');
} ?>

 <!-- Beginning of main page -->
<html><head>
<title>IFRAME Async file uploader example</title>
</head>
<body>
<?php if (isset($msg)) // this is special section for outputing message
    echo '<p style="font-weight: bold;">'.$msg.'</p>';?>
<h1>Upload file:</h1>
<p>File will begin to upload just after selection. </p>
<p>You may write file description, while you file is being uploaded.</p>

<form action="<?=$PHP_SELF?>" target="upload_iframe" method="post" enctype="multipart/form-data">
<input type="hidden" name="fileframe" value="true">
<!-- Target of the form is set to hidden iframe -->
<!-- From will send its post data to fileframe section of
     this PHP script (see above) -->

<label for="file">text file uploader:</label><br>
<!-- JavaScript is called by OnChange attribute -->
<input type="file" name="file" id="file" onChange="jsUpload(this)">
</form>
<script type="text/javascript">
/* This function is called when user selects file in file dialog */
function jsUpload(upload_field)
{
    // this is just an example of checking file extensions
    // if you do not need extension checking, remove
    // everything down to line
    // upload_field.form.submit();

    var re_text = /\.txt|\.xml|\.zip/i;
    var filename = upload_field.value;

    /* Checking file type */
    if (filename.search(re_text) == -1)
    {
        alert("File does not have text(txt, xml, zip) extension");
        upload_field.form.reset();
        return false;
    }

    upload_field.form.submit();
    document.getElementById('upload_status').value = "uploading file...";
    upload_field.disabled = true;
    return true;
}
</script>
<iframe name="upload_iframe" style="width: 400px; height: 100px; display: none;">
</iframe>
<!-- For debugging purposes, it's often useful to remove
     "display: none" from style="" attribute -->

<br>
Upload status:<br>
<input type="text" name="upload_status" id="upload_status"
       value="not uploaded" size="64" disabled>
<br><br>

File name:<br>
<input type="text" name="filenamei" id="filenamei" value="none" disabled>

<form action="<?=$PHP_SELF?>" method="POST">
<!-- one field is "disabled" for displaying-only. Other, hidden one is for
    sending data -->
<input type="hidden" name="filename" id="filename">
<br><br>

<label for="photo">File description:</label><br>
<textarea rows="5" cols="50" name="description"></textarea>

<br><br>
<input type="submit" id="upload_button" value="save file" disabled>
</form>
<br><br>
<a href="<?=$web_upload_dir?>/upload-log.html">upload-log</a>
<br><br><br>

</body>
</html>

If any error or queries drop it in comment section.

Saturday, 6 September 2014

Ajax - Epic outcome of web

Asynchronous JavaScript and XML - AJAX

Ajax is of the most important technologies for the development of highly interactive web application and due to its features it have become extremely popular these days.

What is Ajax?
                    Asynchronous JavaScript and XML or Ajax for short is new web development technique used for the development of most interactive website. Ajax helps you in making your web application more interactive by retrieving small amount of data from web server and then showing it on your application. You can do all these things without refreshing your page
                     Usually in all the web applications, the user enters the data into the form and then clicks on the submit button to submit the request to the server. Server processes the request and returns the view in new page ( by reloading the whole page). This process is inefficient, time consuming, and a little frustrating for you user if the only the small amount of data exchange is required. For example in an user registration form, this can be frustrating thing for the user, as whole page is reloaded only to check the availability of the user name. Ajax will help in making your application more interactive. With the help of Ajax you can tune your application to check the availability of the user name without refreshing the whole page.

Understanding the technology behind Ajax
                            Ajax is not a single technology, but it is a combination of many technologies. These technologies are supported by modern web browsers. Following are techniques used in the Ajax applications.
  • JavaScript:
    JavaScript is used to make a request to the web server. Once the response is returned by the webserver, more JavaScript can be used to update the current page. DHTML and CSS is used to show the output to the user. JavaScript is used very heavily to provide the dynamic behavior to the application.
     
  • Asynchronous Call to the Server:
    Most of the Ajax application used the XMLHttpRequest object to send the request to the web server. These calls are Asynchronous and there is no need to wait for the response to come back. User can do the normal work without any problem.
      
  • XML:
    XML may be used to receive the data returned from the web server. JavaScript can be used to process the XML data returned from the web server easily.
How Ajax Works?
                   When user first visits the page, the Ajax engine is initialized and loaded. From that point of time user interacts with Ajax engine to interact with the web server. The Ajax engine operates asynchronously while sending the request to the server and receiving the response from server. Ajax life cycle within the web browser can be divided into following stages:
  • User Visit to the page:  User visits the URL by typing URL in browser or clicking a link from some other page.
     
  • Initialization of Ajax engine:
    When the page is initially loaded, the Ajax engine is also initialized. The Ajax engine can also be set to continuously refresh the page content without refreshing the whole page.
     
  • Event Processing Loop:
    * Browser event may instruct the Ajax engine to send request to server and receive the response data
    * Server response - Ajax engine receives the response from the server. Then it calls the JavaScript call back functions
    * Browser (View) update - JavaScript request call back functions is used to update the browser. DHTML and css is used to update the browser display.
Benefits of Ajax
Ajax is new very promising technology, which has become extremely popular these days. Here are the benefits of using Ajax:
  • Ajax can be used for creating rich, web-based applications that look and works like a desktop application
     
  • Ajax is easy to learn. Ajax is based on JavaScript and existing technologies like XML, CSS, DHTML. etc. So, its very easy to learn Ajax
      
  • Ajax can be used to develop web applications that can update the page data continuously without refreshing the whole page
Keeping watching for more tutorials from roseindia.net