title: Uploading xml file to server using Android Service
body: <p>I am developing an application in android wrein I call a service that will upload a xml file to the server on click of a button.Problem is when I click the button first time it dosent get uploaded but when I click the button second time its gets uploaded...so let me know if there is any solution..pls help me.</p>
  
  <p>Here is code below which extends service</p>
  
  <pre><code>import java.io.BufferedReader;
  import java.io.ByteArrayOutputStream;
  import java.io.InputStreamReader;
  import java.net.URL;
  import java.text.SimpleDateFormat;
  import java.util.Date;
  
  import android.app.Service;
  import android.content.Intent;
  import android.graphics.Bitmap;
  import android.graphics.BitmapFactory;
  import android.os.Handler;
  import android.os.IBinder;
  import android.util.Base64;
  import android.util.Log;
  import android.widget.Toast;
  
  public class Uploader extends Service
  {
      String info;
      String phot_loc;
      int category;
      String phonenumber = null,profile_name=null,email_id=null;
      double longi;
      double latti;
      Runnable runner;
  
  
      //UIhandler to display the status of upload on response from server
      Handler uiHandler = new Handler();
  
      @Override
      public IBinder onBind(Intent arg0) {
          // TODO Auto-generated method stub
          return null;
      }
  
      @Override
      public void onStart(Intent intent, int startId) {
          // TODO Auto-generated method stub
          super.onStart(intent, startId);
          if(intent!=null)
          {
              info=intent.getStringExtra("info");
              phot_loc=intent.getStringExtra("photo_loc");
              category=intent.getIntExtra("category",0);
              phonenumber=intent.getStringExtra("phone_number");
              profile_name=intent.getStringExtra("profile_name");
              email_id=intent.getStringExtra("email_id");
              longi=intent.getDoubleExtra("longitude",0);
              latti=intent.getDoubleExtra("latitude",0);
              phonenumber=intent.getStringExtra("phone_number");
              Log.d("UploadService","Indide upload Activity");
  
              Thread t=new Thread(runner);
              t.start();
          }
  
          //this will perform the uploading process
          runner=new Runnable(){
  
              @Override
              public void run() {
                  // TODO Auto-generated method stub
              try
              {
  
                  Log.d("UploadService","Indide upload Activity RIUNNER");
  
  
                  String xml = createXml();
  
                  RestClient client = new RestClient("http://3pixelart.com/complaint_process.php",xml);
                  //Log.d("UploadService", xml);
  
                  try {
                        client.Execute();
                        MyRunnable r = new MyRunnable("Complaint Uploaded Successfully");
                          uiHandler.post(r);
                  }
                  catch(Exception e)
                  {
                      Log.e("UploadService", "Exception in uploading :"+e.getMessage());
                      MyRunnable r = new MyRunnable("There was an error while registering complaint. Pls try again "+ e.getMessage());
                      uiHandler.post(r);
  
                  }
  
              }
              catch(Exception e)
              {
                  Log.e("UploadService", "Exception:"+e.getMessage());
                  MyRunnable r=new MyRunnable("Error in uploading the complaint..");
                  uiHandler.post(r);
              }
  
              }
  
  
  
          };
  
  
  
  
      }
  
      public String createXml() {
  
  
           Log.d("UploadService","Indide upload Activity  create xml 1");
  
  
               Log.d("UploadService","Indide upload Activity  create xml 2");
  
              Date d = new Date();
  
              //SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm a");
  
              //String time = formatter.format(d);
  
               Log.d("UploadService","Indide upload Activity  create xml 3");
              String imageData = getBase64ImageData();
  
              SimpleDateFormat fileNameFormatter = new SimpleDateFormat("ddMMyyHHmm");
  
               Log.d("UploadService","Indide upload Activity  create xml 5");
  
              String filename = "image"+fileNameFormatter.format(d)+".png";
  
  
              String finaldata="&lt;?xml version=\"1.0\"?&gt;";
              finaldata+="&lt;ClientRequest&gt;&lt;MobileNumber&gt;"+phonenumber+"&lt;/MobileNumber&gt;&lt;Longitude&gt;";
              finaldata+=longi+"&lt;/Longitude&gt;&lt;Lattitude&gt;"+latti+"&lt;/Lattitude&gt;";
              finaldata+="&lt;Category&gt;"+category+"&lt;/Category&gt;";
              finaldata+="&lt;Profilename&gt;"+profile_name+"&lt;/Profilename&gt;&lt;Email&gt;"+email_id+"&lt;/Email&gt;";
              finaldata+="&lt;FileName&gt;"+filename+"&lt;/FileName&gt;&lt;Image&gt;"+imageData+"&lt;/Image&gt;&lt;Info&gt;";
              finaldata+=info+"&lt;/Info&gt;&lt;/ClientRequest&gt;";
  
              Log.d("UploadService","The DATA IS :  "+finaldata);
              return finaldata;
  
          }
  
  
      private String getBase64ImageData() {
          // TODO Auto-generated method stub
  
      BitmapFactory.Options options = new BitmapFactory.Options(); 
      options.inSampleSize = 8; 
              Bitmap bitmapOrg = BitmapFactory.decodeFile(phot_loc,options);
              ByteArrayOutputStream bao = new ByteArrayOutputStream();
              bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
              byte [] ba = bao.toByteArray();
  
              String encodedImage = Base64.encodeToString(ba, Base64.DEFAULT);
              //Log.d("UploadService", encodedImage);
              bitmapOrg=null;
              System.gc();
          return encodedImage;
      }
  
  
      //this is used to display the status of uploading for this u require UIHandler
      public class MyRunnable implements Runnable{
          private String message=null;
  
          public MyRunnable(String message) {
              // TODO Auto-generated constructor stub
              this.message=message;
          }
          public void run() {
              Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
          }
      };
  
  
  
  
  }
  </code></pre>
  
  <p>and this is my activity which strats that service</p>
  
  <pre><code>import java.util.List;
  
  import android.app.Activity;
  import android.content.Context;
  import android.content.Intent;
  import android.database.Cursor;
  import android.database.sqlite.SQLiteDatabase;
  import android.graphics.Bitmap;
  import android.graphics.BitmapFactory;
  import android.location.Location;
  import android.location.LocationListener;
  import android.location.LocationManager;
  import android.net.Uri;
  import android.os.Bundle;
  import android.provider.MediaStore;
  import android.util.Log;
  import android.view.View;
  import android.view.View.OnClickListener;
  import android.widget.Button;
  import android.widget.EditText;
  import android.widget.ImageView;
  import android.widget.Toast;
  
  public class ComplaintActivity extends Activity implements OnClickListener
  {
  
      boolean pic_taken=false;
      Button bpicture,bregister;
      EditText description;
      ImageView iv1;
      int category=0;
      private static final int TAKE_PICTURE = 1;
      String Provider_name="";
      Location currentLocation;
  
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          // TODO Auto-generated method stub
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_complaint);
  
          bpicture=(Button) findViewById(R.id.button1);
          bregister=(Button) findViewById(R.id.button2);
          iv1=(ImageView) findViewById(R.id.taken_pic);
          description=(EditText)findViewById(R.id.editText1);
  
          bpicture.setOnClickListener(ComplaintActivity.this);
          bregister.setOnClickListener(ComplaintActivity.this);
  
          LocationManager manager=(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
          List &lt;String&gt; l1=manager.getProviders(true);
          if(l1.contains(LocationManager.GPS_PROVIDER))
          {
              Provider_name=LocationManager.GPS_PROVIDER;
  
          }
          if(l1.contains(LocationManager.NETWORK_PROVIDER))
          {
              Provider_name=LocationManager.NETWORK_PROVIDER;
          }
  
          currentLocation=manager.getLastKnownLocation(Provider_name);
          Toast.makeText(ComplaintActivity.this, "GPS PROVIDERS "+Provider_name+"Lattti:"+currentLocation.getLatitude()+"Long:"+currentLocation.getLongitude(), Toast.LENGTH_LONG).show();
          LocationListener listener=new MyLocationListener();
          manager.requestLocationUpdates(Provider_name, 0, 0, listener);
  
  
  
  
      }
  
      class MyLocationListener implements LocationListener
      {
  
          @Override
          public void onLocationChanged(Location location) {
              // TODO Auto-generated method stub
              currentLocation=location;
  
          }
  
          @Override
          public void onProviderDisabled(String provider) {
              // TODO Auto-generated method stub
  
          }
  
          @Override
          public void onProviderEnabled(String provider) {
              // TODO Auto-generated method stub
  
          }
  
          @Override
          public void onStatusChanged(String provider, int status, Bundle extras) {
              // TODO Auto-generated method stub
  
          }
  
      }
  
      @Override
      public void onClick(View arg0) {
          // TODO Auto-generated method stub
  
          if(arg0==bpicture)
              take_picture();
          if(arg0==bregister)
              register_complaint();
  
      }
  
  
      private void take_picture() {
          // TODO Auto-generated method stub
          Intent int_cam=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
          Uri Outputfile=Uri.parse("file:///sdcard/temppic.jpg");
          int_cam.putExtra(MediaStore.EXTRA_OUTPUT,Outputfile);
          startActivityForResult(int_cam,TAKE_PICTURE);
      }
  
      @Override
      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
          // TODO Auto-generated method stub
          super.onActivityResult(requestCode, resultCode, data);
          //Log.d("BAKRA","INSIDE CAMEra Activity&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;");
          if(requestCode==1)
          {
              //Log.d("BAKRA","INSIDE FIRST IF  &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;");
              if(resultCode==RESULT_OK)
              {
              //  Log.d("BAKRA","INSIDE SECONG IF  &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;");
                  if(data==null)
                  {
                  //  Log.d("BAKRA","INSIDE THIRD IF  &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;");
                      pic_taken=true;
                      BitmapFactory.Options opt=new BitmapFactory.Options();
                      opt.inSampleSize=8;
                      Bitmap bitorg=BitmapFactory.decodeFile("sdcard/temppic.jpg", opt);
                  //  Log.d("BAKRA","INSIDE CAME&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;");
                      iv1.setImageBitmap(bitorg);
  
                  }
              }
  
          }
      }
  
      private void register_complaint() {
          // TODO Auto-generated method stub
  
          if(!pic_taken)
          {
              Toast.makeText(ComplaintActivity.this, "Please Take the Picture Related to the Query", Toast.LENGTH_LONG).show();
              return;
          }
          if(description.getText().toString().equals(""))
          {
              Toast.makeText(ComplaintActivity.this, "Please Enter Details About the Complaint",Toast.LENGTH_LONG).show();
              return;
          }
          else
          {
              Intent up=new Intent(ComplaintActivity.this,Uploader.class);
              up.putExtra("category",getIntent().getIntExtra("Selected",1));
              up.putExtra("info", description.getText().toString());
              up.putExtra("photo_loc", "/sdcard/temppic.jpg");
              up.putExtra("latitude", currentLocation.getLatitude());
              up.putExtra("longitude", currentLocation.getLongitude());
  
              SQLiteDatabase db=openOrCreateDatabase("LBA", MODE_PRIVATE, null);
              Cursor c=db.rawQuery("select * from users", null);
              String phonenumber = null,profile_name=null,email_id=null;
              if(c.moveToFirst())
              {
  
                  profile_name=c.getString(c.getColumnIndex("profilename"));
                  email_id=c.getString(c.getColumnIndex("emailid"));
                  phonenumber=c.getString(c.getColumnIndex("phonenumber"));
              }
              up.putExtra("phone_number", phonenumber);
              up.putExtra("profile_name", profile_name);
              up.putExtra("email_id", email_id);
              startService(up);
              Toast.makeText(ComplaintActivity.this, "Uploading to Server...",Toast.LENGTH_LONG).show();
              finish();
          }
  
      }
  
  
  
  
  
  }
  </code></pre>