Pages

Wednesday 31 July 2013

AsyncTask in android

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

Read this fully more about AsyncTask

Coding:

public class Login extends Activity {

 LinearLayout Signin;

 protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
        setContentView(R.layout.login_main);


Signin = (LinearLayout) findViewById(R.id.signin_ll);

Signin.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View arg0) {
// TODO Auto-generated method stub

                  myasynctask MAT = new myasynctask();
   MAT.execute();

   }
});

}

 class myasynctask extends AsyncTask<String, Void, String> {

       @Override
protected String doInBackground(String... params) {
   // TODO Auto-generated method stub
           //Background process like downloading, webservices etc...
           Log.d("doInBackground", "backgroundprocess is ongoing");
          return value;
}

        @Override
public void onPostExecute(String result) {
   // TODO Auto-generated method stub
             Log.d("PostExecute", "after finished the backgroundprocess");
   super.onPostExecute(result);
}

@Override
protected void onPreExecute() {
   // TODO Auto-generated method stub
            Log.d("PreExecute", "before going to start the backgroundprocess");
   super.onPreExecute();
}
}
}

Friday 26 July 2013

Cosume PHP(GET METHOD) webservice in android.

Here i am going to show you the exact code for cosume php webservice in android. But in this example i have passes emailid and password in the url to check whether the user is valid or not.
To consume php get method we will use HttpGet.

Get the response InputStream like this:

InputStream is = null;

HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

Full Code:

  InputStream is = null;
JSONObject jObj = null;
String json = "";

       //Place your own url here
String URL = "http://domain.com/login.php?email="
+ username.getText().toString().trim().toLowerCase()
+ "&password="
+ password.getText().toString().trim().toLowerCase() + "";

   Log.d("username", username.getText().toString().trim()
   .toLowerCase());
   Log.d("password", password.getText().toString().trim()
   .toLowerCase());

   // Making HTTP request
   // (http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/)

   try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);

Log.d("pre", URL);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

   } catch (UnsupportedEncodingException e) {
e.printStackTrace();
   } catch (ClientProtocolException e) {
e.printStackTrace();
   } catch (IOException e) {
e.printStackTrace();
   }

   try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
   sb.append(line + "n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
   } catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
   }

   // try parse the string to a JSON object
   try {
jObj = new JSONObject(json);
   } catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
   }

   // return JSON String

   Log.d("test", jObj.toString());


Manifest.xml:

Add the following line in your manifest.
<uses-permission android:name="android.permission.INTERNET"/>

convert httpresponse to string android 

Consume .net webservice in android



This simple example demonstrates how we can access a .net web service  from Android application.

 XML:

<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" >

    <Button
        android:id="@+id/web_service"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="112dp"
        android:layout_marginTop="146dp"
        android:text="Web Service" />

    <TextView
        android:id="@+id/fetch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="TextView" />

    <ImageView
        android:id="@+id/fetch_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/fetch"
        android:layout_below="@+id/fetch"
        android:layout_marginTop="52dp"
        android:src="@drawable/ic_action_search" />

</RelativeLayout>

Activity:

public class MainActivity extends Activity {

Button web_service;
TextView fetch_service;

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

fetch_service = (TextView) findViewById(R.id.fetch);
web_service = (Button) findViewById(R.id.web_service);
web_service.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
myasynctask MAT = new myasynctask();
MAT.execute();
}
});
}

class myasynctask extends AsyncTask<String, Void, String> {

String str;
private static final String SOAP_ACTION = "http://tempuri.org/CelsiusToFahrenheit";
private static final String METHOD_NAME = "CelsiusToFahrenheit";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://www.w3schools.com/webservices/tempconvert.asmx";

@Override
protected String doInBackground(String... params) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("Celsius", "32");

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);

HttpTransportSE ht = new HttpTransportSE(URL);

try {
ht.call(SOAP_ACTION, envelope);
final SoapPrimitive response = (SoapPrimitive) envelope
.getResponse();
str = response.toString();

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

}
Log.d("WebRespone", str);
return str;
}

@Override
public void onPostExecute(String result) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
fetch_service.setText(result);
super.onPostExecute(result);
}

@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}

}
}
Manifest:
add the following thins in your manifest
 <uses-permission android:name="android.permission.INTERNET"/>

To Do:

You Must add this KSOAP jar file in your Lib folder




Recording Video in android


To access the video recording by using intent We use MediaStore.ACTION_VIDEO_CAPTURE  in Intent function.

     
Function

Intent(MediaStore.ACTION_VIDEO_CAPTURE).
startActivityForResult

     Coding Part:

           XML:

       <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/username"
        android:layout_centerHorizontal="true"
        android:textStyle="bold"
        android:text="Click" />

Activity:
        public class Recording extends Activity {

           Button clickBtn;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.menu);
        clickBtn=(Button)findViewById(R.id.button1);

clickBtn.setOnClickListener(new OnClickListener() {
   
      @Override
      public void onClick(View v) {
   // TODO Auto-generated method stub
      public void onClick(View arg0) {
 Intent takePicture = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(takePicture, 0);

              }
});
}
 }

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
                 super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

                 switch(requestCode) {
                 case 0:
                     if(resultCode == RESULT_OK){
                     Uri selectedImage = imageReturnedIntent.getData();
                             String[] filePathColumn = {MediaStore.Images.Media.DATA};

                                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                                cursor.moveToFirst();

                                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                               //file path of captured image
                                filePath = cursor.getString(columnIndex);
                                //file path of captured image
                                File f = new File(filePath);
                                filename= f.getName();
                             
                                Toast.makeText(getApplicationContext(), "Your Path:"+filePath, 2000).show();
                                Toast.makeText(getApplicationContext(), "Your Filename:"+filename, 2000).show();
                                cursor.close();
                                 
                              //Convert file path into bitmap image using below line.
                               // yourSelectedImage = BitmapFactory.decodeFile(filePath);
                             Toast.makeText(getApplicationContext(), "Your image"+yourSelectedImage, 2000).show();
                             
                               //put bitmapimage in your imageview
                               //yourimgView.setImageBitmap(yourSelectedImage);  


}
                     break;
                     }}}

Add these things in your android.manifest:


    <uses-permission android:name="android.permission.RECORD_VIDEO" />

Recording audio in android



To access the recording by using intent We use Intent.ACTION_GET_CONTENT in Intent function.
Then, We have to set type to intent.setType("audio/*").
       
Function

Intent(Intent.ACTION_GET_CONTENT).
setType("audio/*").
startActivityForResult

     Coding Part:

           XML:

       <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/username"
        android:layout_centerHorizontal="true"
        android:textStyle="bold"
        android:text="Click" />

Activity:

        public class Recording extends Activity {

           Button clickBtn;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.menu);
        clickBtn=(Button)findViewById(R.id.button1);

clickBtn.setOnClickListener(new OnClickListener() {
 
      @Override
      public void onClick(View v) {
   // TODO Auto-generated method stub
      public void onClick(View arg0) {
 Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("audio/*");
    startActivityForResult(intent, 0);
              }
});
}
 }

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
                 super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

                 switch(requestCode) {
                 case 0:
                     if(resultCode == RESULT_OK){
                     Uri selectedImage = imageReturnedIntent.getData();
                             String[] filePathColumn = {MediaStore.Images.Media.DATA};

                                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                                cursor.moveToFirst();

                                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                               //file path of captured image
                                filePath = cursor.getString(columnIndex);
                                //file path of captured image
                                File f = new File(filePath);
                                filename= f.getName();
                             
                                Toast.makeText(getApplicationContext(), "Your Path:"+filePath, 2000).show();
                                Toast.makeText(getApplicationContext(), "Your Filename:"+filename, 2000).show();
                                cursor.close();
                               
                              //Convert file path into bitmap image using below line.
                               // yourSelectedImage = BitmapFactory.decodeFile(filePath);
                             Toast.makeText(getApplicationContext(), "Your image"+yourSelectedImage, 2000).show();
                           
                               //put bitmapimage in your imageview
                               //yourimgView.setImageBitmap(yourSelectedImage);  


}
                     break;
                     }}}

Add these things in your android.manifest:


    <uses-permission android:name="android.permission.RECORD_AUDIO" />

Camera Intent in android.



·         To access the camera by using intent We use MediaStore.ACTION_IMAGE_CAPTURE in Intent function.

       
Function

        Intent(MediaStore.ACTION_IMAGE_CAPTURE).
        startActivityForResult.

     Coding Part:

 
           XML:

      <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
  
 <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/username"
        android:layout_centerHorizontal="true"
        android:textStyle="bold"
        android:text="Click" />
<ImageView
    android:id="@+id/image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_launcher"
    android:layout_below="@+id/button1"/>
     
</RelativeLayout>

Activity:

       public class MainActivity extends Activity {

    Button clickBtn;
    String filePath, filename;
    Bitmap yourSelectedImage;
    ImageView image;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        clickBtn = (Button) findViewById(R.id.button1);
        image = (ImageView) findViewById(R.id.image);

        clickBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(takePicture, 0);

            }
        });
    }

    protected void onActivityResult(int requestCode, int resultCode,
            Intent imageReturnedIntent) {
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

        switch (requestCode) {
        case 0:
            if (resultCode == RESULT_OK) {
                Uri selectedImage = imageReturnedIntent.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };

                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                // file path of captured image
                filePath = cursor.getString(columnIndex);
                // file path of captured image
                File f = new File(filePath);
                filename = f.getName();

                Toast.makeText(getApplicationContext(),
                        "Your Path:" + filePath, 2000).show();
                Toast.makeText(getApplicationContext(),
                        "Your Filename:" + filename, 2000).show();
                cursor.close();

                // Convert file path into bitmap image using below line.
                // yourSelectedImage = BitmapFactory.decodeFile(filePath);
                // Toast.makeText(getApplicationContext(),
                // "Your image"+yourSelectedImage, 2000).show();
                Bitmap myBitmap = BitmapFactory.decodeFile(f.getAbsolutePath());
                // put bitmapimage in your imageviewyourSelectedImage
                image.setImageBitmap(myBitmap);
                image.setVisibility(View.VISIBLE);


                // To save the file in sdcard
                Savefile(filename, filePath);
            }
        }
    }

    public void Savefile(String name, String path) {

        File direct = new File(Environment.getExternalStorageDirectory()
                + "/MyAppFolder/MyApp/");

        File file = new File(Environment.getExternalStorageDirectory()
                + "/MyAppFolder/MyApp/" + name);
        if (!direct.exists()) {
            direct.mkdir();
        }

        if (!file.exists()) {
            try {
                file.createNewFile();
                FileChannel src = new FileInputStream(path).getChannel();
                FileChannel dst = new FileOutputStream(file).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();


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

}



Add these things in your android.manifest:

//Camera
    <uses-permission android:name="android.permission.CAMERA" />

    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />

//for sdcard
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


Thursday 25 July 2013

Fetching image from GALLERY



  •   To fetching image from the gallery. We use Intent.ACTION_GET_CONTENT in Intent function.
  •   Then, We have to set type to intent.setType("image/*").

            Function

  •             Intent(Intent.ACTION_GET_CONTENT).
  •             setType("image/*").
  •    startActivityForResult.

  
       Coding Part:

                 XML:

       <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/username"
        android:layout_centerHorizontal="true"
        android:textStyle="bold"
        android:text="Click" />

       Activity:

       public class Gallery extends Activity {

    Button clickBtn;

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

 clickBtn=(Button)findViewById(R.id.button1);

clickBtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
//TODO Auto-generated method stub

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                     intent.setType("image/*");
                     startActivityForResult(intent, 0);
}
});


     protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
          super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

          switch(requestCode) {
          case 0:
              if(resultCode == RESULT_OK){
                  Uri selectedImage = imageReturnedIntent.getData();

                  String[] filePathColumn = {MediaStore.Images.Media.DATA};
                  Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);

                  cursor.moveToFirst();

                  int columnIndex = cursor.getColumnIndex(filePathColumn[0]);

                 //file path of selected image
                  filePath = cursor.getString(columnIndex);
                  File f = new File(filePath);
                  filename= f.getName();
               
                  Toast.makeText(getApplicationContext(), "Your Path:"+filePath, 2000).show();
                  Toast.makeText(getApplicationContext(), "Your Filename:"+filename, 2000).show();
                  cursor.close();
           
   
              }
              break;
}
     }
}
}

IN MANIFEST:

Add the following things to your Manifest.
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />






How to fetch the value from the text box in android


In your XML:

            <EditText
                android:id="@+id/username"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_centerHorizontal="true"
                android:hint="Fetch the Value"
        />
         
            <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/username"
        android:layout_centerHorizontal="true"
        android:textStyle="bold"
        android:text="Click" />

(@+id/username)This is the id of the text box. Read this fully to declare id in XML layout.


In your Activity:

//To declare your EditText
   EditText fetch;
   String fetchValue;
   Button clickBtn;

   @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_layout);
     
 //binding editbox id with your activity
         fetch=(EditText)findViewById(R.id.username);
//to get the value from the textbox
         fetchValue=fetch.getText().toString();

      clickBtn=(Button)findViewById(R.id.button1);

clickBtn.setOnClickListener(new OnClickListener() {
 
   @Override
   public void onClick(View v) {
// TODO Auto-generated method stub
 Toast.makeText(getApplicationContext(),fetchValue, Toast.LENGTH_LONG).show();
   }
});



}
Read more about Toast.

Android Installation.




  1.  Setting up the Android development environment
  2.  Installing the Java Development Kit
  3.  Installing the Eclipse IDE
  4.  Installing the Android SDK
  5.  Installing the Eclipse Android plugin

This is the procedure to install the android with eclipse. for more Reference.
OR
Easy and simple one recommended by android.
Note:
To browse your db. You should put this plugin in your eclipse plugin folder.