Search This Blog

Saturday, November 23, 2013

Get the Original file path From the Uri in the OnActivity Result

First of all pass the Intent to pick the image from the external storage.. or gelllary

Intent intent = new Intent(Intent.ACTION_PICK, 
      Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(intent, 0);


OnActivityResult write the following code snippet

@Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  
  if(resultCode == RESULT_OK){
   
   image.setImageBitmap(null);
   
   //Uri return from external activity
   orgUri = data.getData();
   text1.setText("Returned Uri: " + orgUri.toString() + "\n");
   
   //path converted from Uri
   convertedPath = getRealPathFromURI(orgUri);
   text2.setText("Real Path: " + convertedPath + "\n");
   
   //Uri convert back again from path
   uriFromPath = Uri.fromFile(new File(convertedPath));
   text3.setText("Back Uri: " + uriFromPath.toString() + "\n");
  }
  
 }

Getting the real path of the Image using the Uri returned in OnActivityResult...

public String getRealPathFromURI(Uri contentUri) {
  String[] proj = { MediaStore.Images.Media.DATA };
  
  //This method was deprecated in API level 11
  //Cursor cursor = managedQuery(contentUri, proj, null, null, null);
  
  CursorLoader cursorLoader = new CursorLoader(
            this, 
            contentUri, proj, null, null, null);        
  Cursor cursor = cursorLoader.loadInBackground();
  
  int column_index = 
    cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
  cursor.moveToFirst();
  return cursor.getString(column_index); 
 }

List of Files in the Directory with specified type

Pass the File Directory in the method and extension if you want to get the files with different file extensions.

 private File[] getJpgFiles(File f){

  File[] files = f.listFiles(new FilenameFilter(){

   @Override
   public boolean accept(File dir, String filename) {
    return filename.toLowerCase().endsWith(".jpg");
   }});
  
  return files;
 }

Delete Directory with its all the inner file and Directories

This is the simple method to remove all the files and folders from the path in the SDcard.

void DeleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory())
for (File child : fileOrDirectory.listFiles())
DeleteRecursive(child);

fileOrDirectory.delete();
}

Unzipping the zip file with the location using ZipInputStream and ZIpEntry

Make a File with the name Decompress.java and add the following code snippet in it.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import android.util.Log;

/**
 * 
 * @author jon
 */
public class Decompress {
private String _zipFile;
private String _location;

public Decompress(String zipFile, String location) {
_zipFile = zipFile;
_location = location;

_dirChecker("");
}

public void unzip() {
try {
FileInputStream fin = new FileInputStream(_zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.v("Decompress", "Unzipping " + ze.getName());

if (ze.isDirectory()) {
_dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(_location
+ ze.getName());
for (int c = zin.read(); c != -1; c = zin.read()) {
fout.write(c);
}

zin.closeEntry();
fout.close();
}

}
zin.close();
deleteDir(_zipFile);
} catch (Exception e) {
Log.e("Decompress", "unzip", e);
}

}

private void _dirChecker(String dir) {
File f = new File(_location + dir);

if (!f.isDirectory()) {
f.mkdirs();
}
}

private void deleteDir(String dir) {
// TODO Auto-generated method stub
File f = new File(dir);
// Util.iLog("delete dir :" + dir);
if (f.exists()) {
f.delete();
}
}
}


Now call these class with the zip file location and unzip location with the following code snippet

Decompress d = new Decompress(zipfileloc, Unziploc);
d.unzip();

Download the large file from the server

Download the large file from the server asynchronously in android with the below code....

call this:

new DownloadFileAsync(YourActivity.this).execute();

And your DownloadFileAsync is as below:

class DownloadFileAsync extends AsyncTask<String, String, String> {

@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}

@Override
protected String doInBackground(String... aurl) {
int count;

try {

// URL url = new URL(DOWNLOAD URL);

URLConnection conexion = url.openConnection();
conexion.connect();

int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

InputStream input = new BufferedInputStream(url.openStream());
File filedir = new File(path);
// have the object build the directory structure, if needed.
filedir.mkdirs();
OutputStream output = new FileOutputStream(path + name + ".zip");

byte data[] = new byte[1024];

long total = 0;

while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile),
name);
output.write(data, 0, count);
}

output.flush();
output.close();
input.close();

} catch (Exception e) {
}
return null;

}

protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
mProgressDialog.setMessage("Downloading " + progress[1] + ".....");
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}

@Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
new UnzipFile(BookDownloadActivity.this, path + name + ".zip", path)
.execute();
}
}

@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file.....");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}


This is how you can download the whole file from the server or any other URLs.

Thursday, August 29, 2013

Run the same AsyncTask after completing itself.

Create an object of the task and execute the same task as following.

UpdateCoin updatecoin = new UpdateCoin();

                    if (updatecoin.getStatus() == AsyncTask.Status.PENDING) {

                    }

                    if (updatecoin.getStatus() == AsyncTask.Status.RUNNING) {

                    }

                    if (updatecoin.getStatus() == AsyncTask.Status.FINISHED) {

                        Runnable myRunner = new Runnable() {
                            public void run() {
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                                    new UpdateCoin().executeOnExecutor(
                                            AsyncTask.THREAD_POOL_EXECUTOR, coin,
                                            LevelUpBonus[level - 1]);
                                } else {
                                    new UpdateCoin().executeOnExecutor(
                                            AsyncTask.THREAD_POOL_EXECUTOR, coin,
                                            LevelUpBonus[level - 1]);
                                }
                            }
                        };
                        myHandler.post(myRunner);
                    }

Tuesday, July 16, 2013

Ecxecute two Different AsyncTask parallel in android

If you want to ecxecute the two different asynctask to be ecxecute parallelly then you shoul use the second async task ecxecution like below.  UpdateCoin is the Async task.         

   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
new UpdateCoin().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
mPref.getInt("UserCoin", 0), CalculatedCoin);
} else {
new UpdateCoin().execute(mPref.getInt("UserCoin", 0), CalculatedCoin);
}

Tuesday, June 4, 2013

Sorting the ArrayList by Name and Value in android

Sorting the ArrayList by String comparison by the Following code.

Collections.sort(name, new Comparator<YOURARRAYLISTNAME>() {
    @Override
    public int compare(Invitation lhs, Invitation rhs) {
     return lhs.getName().compareToIgnoreCase(rhs.getName());
    }
   });


You can also compare Arraylist by INTEGER value by following code:


Collections.sort(value, new Comparator<YOURARRAYLISTNAME>() {
    @Override
    public int compare(Invitation lhs, Invitation rhs) {
                        return (lhs.expenditure < rhs.expenditure ? 1 : -1);
    }
   });

Thursday, May 23, 2013

Validate the String for the Email


Here is the method for checking the String is email address or not.


private boolean checkemail(String emailstr) {
// TODO Auto-generated method stub
boolean isValid = false;
   String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
   CharSequence inputStr = emailstr;
   Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
   Matcher matcher = pattern.matcher(inputStr);
   if (matcher.matches()) {
       isValid = true;
   }
   return isValid;

}

For validate the String use following:

if(checkemail(emailstr)){
  // Here do with the Email string
}else{
  System.out.println("email String is not valid");
}

Thursday, May 9, 2013

Get the number of times app is used




 private SharedPreferences mPref;
public static final String PREFS_NAME = "YourPrefName";
int c;

in onCreate() write the following



  mPref = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
c = mPref.getInt("numRun", 0);
Log.i("TAG", "Number of count of open App:" + c);
c++;
mPref.edit().putInt("numRun", c).commit();
Log.i("TAG", "Number of count after commit of open App:" + c);

Saturday, April 13, 2013

Count Down Timer in android

Android provide a android.os.CountDownTimer. By new a CountDownTimer object, and overriding the call-back function onTick() and onFinish(), you can implement a count down timer easily.

public class CountDownTimerActivity extends Activity {

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

                final TextView myCounter = (TextView)findViewById(R.id.mycounter);
                new CountDownTimer(30000, 1000) {

                                        @Override
                                        public void onFinish() {
                                                         // TODO Auto-generated method stub
                                                         myCounter.setText("completed Timer!");
                                        }

                                       @Override
                                        public void onTick(long millisUntilFinished) {
                                                    // TODO Auto-generated method stub
                                                   myCounter.setText("Millisecond Until Finished: " + String.valueOf(millisUntilFinished));
                                       }

                   }.start(); 
       } 
}

Xml file will be below.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<TextView
android:id="@+id/mycounter"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

</LinearLayout>


Sunday, March 31, 2013

DialogFragment

android.app.DialogFragment, was introduced from API Level 11 (Android 3.0), displays a dialog window, floating on top of its activity's window.


public class MyDialogFragment extends DialogFragment {

            static MyDialogFragment newInstance() {

            String title = "My Fragment";

            MyDialogFragment f = new MyDialogFragment();
            Bundle args = new Bundle();
            args.putString("title", title);
            f.setArguments(args);
            return f;
            }

            @Override
            public Dialog onCreateDialog(Bundle savedInstanceState) {
                            String title = getArguments().getString("title");
                            Dialog myDialog = new AlertDialog.Builder(getActivity())
                                                   .setIcon(R.drawable.ic_launcher)
                                                   .setTitle(title)
                                                   .setPositiveButton("OK", 

                                                      new DialogInterface.OnClickListener() {
                     @Override
                     public void onClick(DialogInterface dialog, int which) {
                                      ((AndroidDialogFragmentActivity)getActivity()).okClicked();
                    }
                })
                                                  .setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {

                   @Override
                   public void onClick(DialogInterface dialog, int which) {
                                      ((AndroidDialogFragmentActivity)getActivity()).cancelClicked();
                   }
               })
              .create();

return myDialog;
}

}


in main.xml modify the following code.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Button
android:id="@+id/opendialog"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Open Dialog" />

</LinearLayout>


now in your activity just change the following code and see the dialog

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


                                Button buttonOpenDialog = (Button)findViewById(R.id.opendialog);
                                buttonOpenDialog.setOnClickListener(new Button.OnClickListener(){

                               @Override
                               public void onClick(View arg0) {
                                                  OpenDialog();
                                }});

                  }

                  void OpenDialog(){
                         MyDialogFragment myDialogFragment = MyDialogFragment.newInstance();
                         myDialogFragment.show(getFragmentManager(), "myDialogFragment");
                  }

                 public void okClicked() {
                          Toast.makeText(AndroidDialogFragmentActivity.this,
                                           "OK Clicked!",
                                           Toast.LENGTH_LONG).show();
                 }

                 public void cancelClicked() {
                                  Toast.makeText(AndroidDialogFragmentActivity.this,
                                                 "Cancel Clicked!",  Toast.LENGTH_LONG).show();
                  }
}

Draw bar chart in android

This is the same as the Last Tutorial i have posted. We just need to implement the following code in the View instead of the last tutorial.


public class DrawBarChart extends View {
Paint paint = new Paint();
int c[] = { Color.BLUE, Color.RED };
Canvas mCanvas = new Canvas();
private float[] val_exp;
private float[] val_inco;
Context context;
WindowManager mWinMgr;

public DrawBarChart(Context context) {
super(context);
paint = new Paint();
super.draw(mCanvas);
}

public DrawBarChart(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
super.draw(mCanvas);
}

public DrawBarChart(Context context, float[] val_exp, float[] val_inco) {
super(context);
paint = new Paint();
this.val_exp = val_exp;
this.val_inco = val_inco;
super.draw(mCanvas);
}

public void draw(Canvas canvas) {
int x = getWidth();
int y = getHeight();
float max = getMax();
paint.setColor(Color.parseColor("#78777D"));
paint.setStyle(Style.STROKE);
paint.setStrokeWidth(2);
canvas.drawRect(0, 0, x - 1, y - 1, paint);
int n = val_exp.length;
int gap = x / 12;
paint.setStyle(Style.FILL);
for (int i = 0; i < n; i++) {

paint.setColor(Color.BLACK);
//Bottom Numbers 1 to 12.
canvas.drawText("" + (i + 1), i * gap + (gap / 2), y - 5, paint);    

//Vertical Lines.
canvas.drawLine((float) (i + 0.5) * gap + 4, y - 15,
(float) (i + 0.5) * gap + 4, y - 25, paint);    
            
// Blue bars for Income.
paint.setColor(Color.BLUE);
canvas.drawLine(i * gap + 5, y - 20, (float) (i + 0.5) * gap + 3,
y - 20, paint);

float bHeIn =(max==0)?y-20:  y - (val_inco[i] * (y - 22) / max)- 20;

canvas.drawRect((float) i   * gap + 5, bHeIn,
(float) (i + 0.5) * gap + 3, y - 20, paint);

// Red bars for Expenses.
paint.setColor(Color.RED);
canvas.drawLine((float) (i + 0.5) * gap + 5, y - 20,
(float) (i + 1) * gap + 3, y - 20, paint);

float bHeEx =(max==0)?y-20:  y - (val_exp[i] * (y - 22) / max)- 20;

canvas.drawRect((float) (i + 0.5) * gap + 5, bHeEx,
(float) (i + 1) * gap + 3, y - 20, paint);
}
}

private float getMax() {
float max = 0;
for (float f : val_exp) {
if (f > max)
max = f;
}
for (float f : val_inco) {
if (f > max)
max = f;
}
return max;
}
}

And for drawing the chart of the values of the data you need to pass the values to the objects of the class as follow.    


           DrawBarChart barView;
           LinearLayout la;

           barView = new DrawBarChart(this, vals_exp,vals_inco);
          la.addView(barView);

Draw PieChart in android using View

Fitst of all make an Relative layout as the below in your XML file to Display Pie chart on that view.

<RelativeLayout

       android:id="@+id/piechart_lay"
       android:layout_width="150dip"
       android:layout_height="150dip"
       android:layout_margin="5dip"
       android:background="#eeffee"
       android:orientation="horizontal" >
</RelativeLayout>


Now we have to make a View which make the actual pie chart and draw and fill the color in the chart. Create one file let's say DrawPieChart.java extends View and add the following code snippet in it.

public class DrawPieChart extends View {

Paint paint = new Paint();
        //  Here you can Add number of different color according to max different colors to be displayed on Piechart
        int c[] = {Color.MAGENTA,Color.BLUE,Color.RED,Color.CYAN,Color.YELLOW,Color.GREEN};
Canvas mCanvas = new Canvas();
private int[] values;
Context context;

public DrawPieChart(Context context, int[] values) {
super(context);
paint = new Paint();
this.values = values;
// this.labels = labels;
super.draw(mCanvas);
}

public void draw(Canvas canvas) {
int x = getWidth();
int y = getHeight();
float t = getTotal();
paint.setColor(Color.parseColor("#78777D"));
paint.setStyle(Style.STROKE);
paint.setStrokeWidth(2);
canvas.drawRect(0, 0, x - 1, y - 1, paint);
int n = values.length;
float cuurPos = -90;
paint.setStyle(Style.FILL);
RectF rect = new RectF(20,20,x-20,y-20);
for (int i = 0; i < n; i++) {
paint.setColor(c[i]);
float thita =(t==0)?0: 360*values[i]/t;
canvas.drawArc(rect, cuurPos, thita, true, paint);
cuurPos = cuurPos+thita;
}
}

private float getTotal() {
int total = 0;
for (int i = 0; i < values.length; i++) {
total = total + values[i];
}
return total;
}
}

Now create an object of this class in your activity and pass the Array of the values to the object and it will create the Piechart in the Relative layout. You have to add this view in the Activity to your relative layout.


class Piechart extends Activity{


        RelativeLayout la;
DrawPieChart piView;
        int[] vals;


       @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.relative);
                la = (RelativeLayout) findViewById(R.id.pie_lay);
                getPieChart();
        }
        
        public void  getPieChart(){
             vals[] = new vals[YOUR SIZE OF ARRAY];
             vals = {12,14,23,35,23,56,78};
             piView = new DrawPieChart(Analisys.this, vals);
             
             la.removeAllViews();
     la.addView(piView); 
       }
}



Saturday, March 30, 2013

Streaming songs from Url in Default Media Player

Here i am posting with the example code of the streaming the songs from the Url in android with android default media player. 

First of all you just have to make the XML file with the following lines

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:focusable="true">
<EditText 
android:text="The song URL" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:id="@+id/EditTextSongURL"/>
<ImageButton 
android:layout_below="@+id/EditTextSongURL"
android:id="@+id/ButtonTestPlayPause" 
android:layout_height="wrap_content" 
android:layout_width="match_parent"
android:src="@drawable/button_play"/>
<SeekBar 
android:layout_below="@+id/ButtonTestPlayPause"
android:id="@+id/SeekBarTestPlay" 
android:layout_height="wrap_content" 
android:layout_width="match_parent"
android:thumb="@drawable/thumb_transparent"/>
</RelativeLayout>

Now in you main Activity class replace with the following code and enter the URL of your server song and hit play.

public class StreamingPlayer extends Activity implements OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener{

private ImageButton buttonPlayPause;
private SeekBar seekBarProgress;
public EditText editTextSongURL;

private MediaPlayer mediaPlayer;
// this value contains the song duration in milliseconds. Loook at getDuration() method in MediaPlayer class
private int mediaFileLengthInMilliseconds; 

private final Handler handler = new Handler();

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

/** This method initialise all the views in project*/
private void initView() {
             buttonPlayPause = (ImageButton)findViewById(R.id.ButtonTestPlayPause);
             buttonPlayPause.setOnClickListener(this);

             seekBarProgress = (SeekBar)findViewById(R.id.SeekBarTestPlay);
             seekBarProgress.setMax(99); // It means 100% .0-99
             seekBarProgress.setOnTouchListener(this);
             editTextSongURL = (EditText)findViewById(R.id.EditTextSongURL);
             editTextSongURL.setText(R.string.testsong_20_sec);

             mediaPlayer = new MediaPlayer();
             mediaPlayer.setOnBufferingUpdateListener(this);
             mediaPlayer.setOnCompletionListener(this);
}

/** Method which updates the SeekBar primary progress by current song playing position*/
private void primarySeekBarProgressUpdater() {
              seekBarProgress.setProgress((int)                                     (((float)mediaPlayer.getCurrentPosition()/mediaFileLengthInMilliseconds)*100)); // This math construction give a percentage of "was playing"/"song length"
                     if (mediaPlayer.isPlaying()) {
                                     Runnable notification = new Runnable() {
                                                         public void run() {
                                                                    primarySeekBarProgressUpdater();
                                                         }
                                     };
                    handler.postDelayed(notification,1000);
       }
}

@Override
public void onClick(View v) {

           if(v.getId() == R.id.ButtonTestPlayPause){
/** ImageButton onClick event handler. Method which start/pause mediaplayer playing */
             try {
                   // setup song URL to mediaplayer data source
                  mediaPlayer.setDataSource(editTextSongURL.getText().toString());
                  mediaPlayer.prepare();
                 } catch (Exception e) {
                  e.printStackTrace();
               }

mediaFileLengthInMilliseconds = mediaPlayer.getDuration();

           if(!mediaPlayer.isPlaying()){
                mediaPlayer.start();
                buttonPlayPause.setImageResource(R.drawable.button_pause);
           }else {
                mediaPlayer.pause();
                buttonPlayPause.setImageResource(R.drawable.button_play);
          }

          primarySeekBarProgressUpdater();
     }
}

@Override
public boolean onTouch(View v, MotionEvent event) {
           if(v.getId() == R.id.SeekBarTestPlay){
             /** Seekbar onTouch event handler. Method which seeks MediaPlayer to seekBar        primary progress position*/
                    if(mediaPlayer.isPlaying()){
                          SeekBar sb = (SeekBar)v;
                          int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100) * sb.getProgress();
                         mediaPlayer.seekTo(playPositionInMillisecconds);
                    }
               }
          return false;
     }


@Override
public void onCompletion(MediaPlayer mp) {
       /** MediaPlayer onCompletion event handler. Method which calls then song playing is complete*/
           buttonPlayPause.setImageResource(R.drawable.button_play);
}

@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
/** Method which updates the SeekBar secondary progress by current song loading from URL position*/
             seekBarProgress.setSecondaryProgress(percent);
      }
}

Sunday, March 24, 2013

Calling the POST method using the MultipartEntity with Image and Data

Here is the method to post the image and audio File along with the data.

For multipart you need to add the libraries along with the project as below.




1) Download httpcomponents-client-4.1.zip from http://james.apache.org/download.cgi#Apache_Mime4Jand add apache-mime4j-0.6.1.jar to your project.


2) Download httpcomponents-client-4.1-bin.zip from http://hc.apache.org/downloads.cgi and add httpclient-4.1.jar, httpcore-4.1.jar and httpmime-4.1.jar to your project.

and here is the method of the posting the image and data to service.

public int PostMerthodWithImage(byte[] data, String postStr, String pointNumber,
String name, String ext) {
try {
mHttpClient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlString); \\ pass the Url of the webservice here
MultipartEntity multipartEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
Log.i("log_tag", "name :" + name + "  ::::: And Ext :" + ext);

if (data != null) {
bab = new ByteArrayBody(data, name.trim() + ".".trim()
+ ext.trim());
image_video_name = name.trim() + ".".trim() + ext.trim();
multipartEntity.addPart("image_video", bab);
multipartEntity.addPart("image_video_name", new StringBody(
image_video_name, Charset.forName("UTF-8")));
Log.i("log_tag", "At send image_video_name :"
+ image_video_name);
} else {
bab = null;
image_video_name = null;
}
// multipartEntity.addPart("image_video", bab);
// Log.i("log_tag", "At send bytearray :" + bab.toString());
multipartEntity.addPart("point_id", new StringBody(pointNumber,
Charset.forName("UTF-8")));
Log.i("log_tag", "At send point_id :" + pointNumber);
multipartEntity.addPart("user_id",
new StringBody("1", Charset.forName("UTF-8")));
Log.i("log_tag", "At send user_id :" + "1");
multipartEntity.addPart("comment_text", new StringBody(postStr,
Charset.forName("UTF-8")));
Log.i("log_tag", "At send comment_text :" + postStr);
multipartEntity.addPart(
"date",
new StringBody("" + System.currentTimeMillis(), Charset
.forName("UTF-8")));
Log.i("log_tag", "At send date :" + System.currentTimeMillis());
httppost.setEntity(multipartEntity);
HttpResponse response1 = mHttpClient.execute(httppost);
HttpEntity r_entity = response1.getEntity();
String Response = EntityUtils.toString(r_entity);
JSONObject jobj = null;
try {
jobj = new JSONObject(Response);
} catch (JSONException e) {
e.printStackTrace();
}
try {
Joj = jobj.getString("status");
} catch (Exception e) {
}
Log.i("log_tag", "Response from server :" + Response);
mHttpClient.getConnectionManager().shutdown();
} catch (Exception e) {
Log.e(HttppostClient.class.getName(), e.getLocalizedMessage(), e);
}
if (Joj == "1") {
return 1;
} else {
return 0;
}

}

Animation : Fade-In Fade-out


Create XML file for fade-in animation, /res/anim/fadein.xml.


<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">
<alpha
android:fromAlpha="0.1"
android:toAlpha="1.0"
android:duration="2000"
/>
</set>


Create XML file for fade-out animation, /res/anim/fadeout.xml.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">
<alpha
android:fromAlpha="1.0"
android:toAlpha="0.1"
android:duration="2000"
/>
</set>



Modify main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Button
android:id="@+id/fadein"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Fade In"/>
<Button
android:id="@+id/fadeout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Fade Out"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center">

<ImageView
android:id="@+id/image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="@drawable/ic_launcher" />

</LinearLayout>

</LinearLayout>




main activity


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

Button buttonFadeIn = (Button)findViewById(R.id.fadein);
Button buttonFadeOut = (Button)findViewById(R.id.fadeout);
final ImageView image = (ImageView)findViewById(R.id.image);

final Animation animationFadeIn = AnimationUtils.loadAnimation(this, R.anim.fadein);
buttonFadeIn.setOnClickListener(new Button.OnClickListener(){

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

final Animation animationFadeOut = AnimationUtils.loadAnimation(this, R.anim.fadeout);
buttonFadeOut.setOnClickListener(new Button.OnClickListener(){

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


Tween animation: Rotate animation

Create /res/anim/rotate_center.xml for animation of rotating around center
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">
<rotate
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="2000"
android:startOffset="0"/>
</set>


Create /res/anim/rotate_corner.xml for animation of rotating around the upper-left corner


<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">
<rotate
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="0%"
android:pivotY="0%"
android:duration="2000"
android:startOffset="0"/>
</set>



modify main.xml as below.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Button
android:id="@+id/rotatecenter"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Rotate around center"/>
<Button
android:id="@+id/rotatecorner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Rotate around corner"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center">

<ImageView
android:id="@+id/floatingimage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />

</LinearLayout>

</LinearLayout>


main activitypackage com.exercise.AndroidAnimTranslate;

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 AndroidAnimTranslateActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button buttonRotateCenter = (Button)findViewById(R.id.rotatecenter);
Button buttonRotateCorner = (Button)findViewById(R.id.rotatecorner);
final ImageView floatingImage = (ImageView)findViewById(R.id.floatingimage);

final Animation animationRotateCenter = AnimationUtils.loadAnimation(this, R.anim.rotate_center);
buttonRotateCenter.setOnClickListener(new Button.OnClickListener(){

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

final Animation animationRotateCorner = AnimationUtils.loadAnimation(this, R.anim.rotate_corner);
buttonRotateCorner.setOnClickListener(new Button.OnClickListener(){

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