Skip to main content

Upload Photo to server using Android and .Net



In this example with image we are passing some string also like name and description as well as we have Radio button also which is use too map different upload location .
Step by step:-
1>                                                 First will be design which is our XML file name photo_upload.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
     android:orientation="vertical"
    android:fillViewport="true" >

    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="203dp"
        android:background="@color/WhiteSmoke"
        android:orientation="vertical"
        android:scrollbars="vertical" >

        <TableLayout
            android:id="@+id/tableLayout1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
         
            android:orientation="horizontal"
            android:stretchColumns="*" >

            <TableRow>

                <Button
                    android:id="@+id/imguploadbtn"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dip"
                    android:background="@drawable/custom_button_selector"
                    android:text="Upload" />

                <Button
                    android:id="@+id/imgcancelbtn"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dip"
                    android:background="@drawable/custom_button_selector"
                    android:text="Cancel" />
            </TableRow>
        </TableLayout>

        <RelativeLayout
            android:id="@+id/relativeLayout1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:background="@color/White" >

            <RadioGroup
                android:id="@+id/rbgrouptype"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_weight="1"
                android:background="@color/White"
                android:orientation="horizontal" >

                <RadioButton
                    android:id="@+id/rbso"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="@color/Black"
                    android:checked="true"
                    android:gravity="center"
                    android:text="Outbound"
                    android:textColor="@color/White"
                    android:textColorLink="@color/Black" />

                <RadioButton
                    android:id="@+id/rbre"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="@color/Black"
                    android:gravity="center"
                    android:text="Inbound"
                    android:textColor="@color/White" />

                <RadioButton
                    android:id="@+id/rbSku"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="@color/Black"
                    android:gravity="center"
                    android:text="SKU"
                    android:textColor="@color/White" />
            </RadioGroup>
            <EditText
                android:id="@+id/txtosid"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_below="@+id/rbgrouptype"
                android:ems="10"
                android:hint="Enter Doc ID"
                android:textColor="@color/Black" />

            <Spinner
                android:id="@+id/drpDescription"
                android:layout_width="match_parent"
                android:layout_height="40sp"
                android:layout_alignParentLeft="true"
                android:layout_below="@+id/txtosid"
                android:background="@color/Wheat"
             
                android:prompt="@string/reject_prompt"
                android:spinnerMode="dialog"
            />

        </RelativeLayout>

           <ImageView
               android:id="@+id/ImageView"
               android:layout_width="fill_parent"
               android:layout_height="150dp"
               android:layout_above="@+id/tableLayout1"
               android:layout_centerHorizontal="true"
               android:layout_marginBottom="90dp"
               android:background="@color/White"
               android:maxHeight="150dp"
               android:maxWidth="150dp"
               android:scaleType="fitXY"
               android:scrollbars="horizontal|vertical" />

    </RelativeLayout>

</ScrollView>


2>Application manifest file give Internet Permission and you must declare your activity in Manifest file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.login.loginexamplesqllite"
    android:versionCode="1"
    android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
    <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.upload.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>


3>   Now let’s start with some coding   start with  Main_Activity

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import appclasess.GloabVariable;

import com.pack.rsa.ConnectionDetector;
import com.pack.rsa.R;


public class MainActivity extends Activity implements OnCheckedChangeListener, OnItemSelectedListener {


       private static final int PICK_IMAGE = 1;
       private static final int PICK_Camera_IMAGE = 2;
       private static final int PICK_Scan_Code = 3;

      
       private int maxWidth = 70;
       private int maxHeight = 70;
      
       ArrayList<String> INReasonItems = new ArrayList<String>();
       ArrayList<String> OUTReasonItems = new ArrayList<String>();
       ArrayList<String> SKUReasonItems = new ArrayList<String>();
       ConnectionDetector cd;
    private RadioGroup radioupGroup;
       private RadioButton radiosoButton;

        
       private ProgressDialog pDialog;
       public static final int progress_bar_type = 0;
       private ProgressDialog dialog;
       private Spinner spinner;
       private int k=0;
       private ImageView imgView;
       private Button upload,cancel;
       private Bitmap bitmap;
      
       Uri imageUri;
       private EditText docid;
       String imagepath;
    MediaPlayer mp=new MediaPlayer();
    String UType;
    private static int RESULT_LOAD_IMAGE = 1;
    ArrayAdapter<String> dataAdapter,dataAdapter1,dataAdapter2 ;
   
       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.uploaddirect);

              imgView = (ImageView) findViewById(R.id.ImageView);
              upload = (Button) findViewById(R.id.imguploadbtn);
              cancel = (Button) findViewById(R.id.imgcancelbtn);
              docid=(EditText)findViewById(R.id.txtosid);
      
              radioupGroup = (RadioGroup) findViewById(R.id.rbgrouptype);
             
                
            spinner = (Spinner) findViewById(R.id.drpDescription);
            spinner.setOnItemSelectedListener(this);
           
              //Here we are trying to get decription ffrom server
               k=1;
               DownLoadTaskINReason downloadTask1 = new DownLoadTaskINReason();
            downloadTask1.execute(http://www.example.com+"/ getDescription.aspx?Fu=IN");
            if(k==1)
            dataAdapter = new ArrayAdapter<String>(UploadDirect.this,
                     android.R.layout.simple_spinner_item, INReasonItems);
        
             
               ((RadioGroup)findViewById(R.id.rbgrouptype)).setOnCheckedChangeListener(this);

              upload.setOnClickListener(new View.OnClickListener() {

                     public void onClick(View v) {
                                 
                            if (docid.getText().toString().trim().length() <= 0) {
                                  Toast.makeText(getApplicationContext(),
                                                "Please Enter Doc/Order ID", Toast.LENGTH_SHORT).show();
                           }
                            else  if (spinner.getSelectedItem().toString().trim().length() <= 0) {
                                         Toast.makeText(getApplicationContext(),
                                                       "Please Select Valid Description", Toast.LENGTH_SHORT).show();
                                  }
                            else  if (bitmap == null) {
                                  Toast.makeText(getApplicationContext(),
                                                "Please select image", Toast.LENGTH_SHORT).show();
                           }
                           else {
                                  dialog = ProgressDialog.show(UploadDirect.this, "Uploading",
                                                "Please wait...", true);
                                 
                                  int selectedId = radioupGroup.getCheckedRadioButtonId();
                             radiosoButton = (RadioButton) findViewById(selectedId);
                       UType=radiosoButton.getText().toString();
                               Toast.makeText(UploadDirect.this,
                                  radiosoButton.getText(), Toast.LENGTH_SHORT).show();
                              
                               String  url=http://www.example.com+"/ getDescription.aspx?Fu=Validate&uType="+UType+"&customer="+gv.GetCustomerName().toString()+"&docid="+docid.getText().toString()+"";
                                  Log.e("URL", url);
                                   ChechkValidation chk = new ChechkValidation();
                                chk.execute(url);
                              
                           }
                     }
              });

              cancel.setOnClickListener(new OnClickListener() {
                     public void onClick(View v) {
                           // TODO Auto-generated method stub
                           UploadDirect.this.finish();
                     }
              });
             
       }
       //here its validation that document number which we are passing it’s exists or not
       private class ChechkValidation extends AsyncTask<String, Void, String> {
           @Override
           protected String doInBackground(String... urls) {
             String response = "";
             for (String url : urls) {
               DefaultHttpClient client = new DefaultHttpClient();
               HttpGet httpGet = new HttpGet(url);
               try {
                 HttpResponse execute = client.execute(httpGet);
                 InputStream content = execute.getEntity().getContent();

                 BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
                 String s = "";
                 while ((s = buffer.readLine()) != null) {
                   response += s;
                   Log.d("Http Response:", response.toString());
                 }

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

           @Override
           protected void onPostExecute(String result) {
              Log.d("Http Result:", result);
               if(result!=null && result=="TRUE")
                   {
                     new ImageGalleryTask().execute();
                   }
                   else
                   {
                      try {
                                         if (dialog.isShowing())
                                                dialog.dismiss();
                                  } catch (Exception e) {
                                         Toast.makeText(getApplicationContext(),
                                                       e.getMessage(),
                                                       Toast.LENGTH_LONG).show();
                                         Log.e(e.getClass().getName(), e.getMessage(), e);
                                  }
                      Toast.makeText(UploadDirect.this,
                                                "No Such Document Number Exists!", Toast.LENGTH_SHORT).show();
                      docid.setFocusable(true);
                   }
           }
         }

        public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
    
         switch (checkedId) {
         case R.id.rbso:
               INReasonItems.clear();
               
              k=1;

//depend on required function I’m getting description from three different table from server which return json array
             DownLoadTaskINReason downloadTask1 = new DownLoadTaskINReason();
                  downloadTask1.execute(http://www.example.com+"/ getDescription.aspx?Fu=IN");
           
                dataAdapter = new ArrayAdapter<String>(UploadDirect.this,
                     android.R.layout.simple_spinner_item, INReasonItems);
          
                 break;
         case R.id.rbre:
               
               k=2;
               OUTReasonItems.clear();
               
                  DownLoadTaskINReason downloadTask2 = new DownLoadTaskINReason();
           downloadTask2.execute(http://www.example.com +"/getDescription.aspx?Fu=OUT");
      
          dataAdapter1 = new ArrayAdapter<String>(UploadDirect.this,
                     android.R.layout.simple_spinner_item, OUTReasonItems);
            
                 break;
         case R.id.rbSku:
               
                 k=3;
                 SKUReasonItems.clear();
               
                 DownLoadTaskINReason downloadTask3 = new DownLoadTaskINReason();
                 downloadTask3.execute(http://www.example.com +"/getDescription.aspx?Fu=SKU");
          
                dataAdapter2 = new ArrayAdapter<String>(UploadDirect.this,
                     android.R.layout.simple_spinner_item, SKUReasonItems);
                break;
         }
       
 }
       public int UploadFile(){
              int output=0;
              try {
                  // Set your file path here
                  File Directory =new File(imagepath);
                  FileInputStream fstrm = new FileInputStream(Directory);
                  Log.e("path", fstrm.toString());
                  String   fileName = Directory.getName();
                  Log.e("filename",""+ fileName+UType);
                  //Spinner mySpinner = (Spinner)findViewById(R.id.drpDescription);
                  String Text = spinner.getSelectedItem().toString();
                  Log.v("Selecteditem", Text);
                  HttpFileUpload hfu = new HttpFileUpload(gv.url+"/uploadimage.aspx", docid.getText().toString().trim(),Text.toString().replaceAll(" ", "%20").trim(),fileName,gv.GetCustomerName(),UType);
                  Log.e("urlfiletobesend",""+ hfu+UType);
                  hfu.Send_Now(fstrm);
                  return output;
                } catch (FileNotFoundException e) {
                  // Error: File not found
                       return output;
                }
              }
       @Override
        public boolean onCreateOptionsMenu(Menu menu) {
                 MenuInflater inflater = getMenuInflater();
                 inflater.inflate(R.menu.list_menu, menu);
                 return true;
        }
   
       @Override
       public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
               case R.id.camera:
                     //define the file-name to save photo taken by Camera activity
                     String fileName = "new-photo-name.jpg";
                     //create parameters for Intent with filename
                     ContentValues values = new ContentValues();
                     values.put(MediaStore.Images.Media.TITLE, fileName);
                     values.put(MediaStore.Images.Media.DESCRIPTION,"Image captured by camera");
                     //imageUri is the current activity attribute, define and save it for later usage (also in onSaveInstanceState)
                     imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                     //create new Intent
                     Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                     intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                     intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                     startActivityForResult(intent, PICK_Camera_IMAGE);
                   return true;
              
               case R.id.gallery:
                     try {
                           Intent gintent = new Intent();
                           gintent.setType("image/*");
                           gintent.setAction(Intent.ACTION_GET_CONTENT);
                           startActivityForResult(
                           Intent.createChooser(gintent, "Select Picture"),
                           PICK_IMAGE);
                           return true;
                          
                     } catch (Exception e) {
                           Toast.makeText(getApplicationContext(),
                           e.getMessage(),
                           Toast.LENGTH_LONG).show();
                           Log.e(e.getClass().getName(), e.getMessage(), e);
                     }
               case R.id.Scanbarcode:
                     try
                     {
                            //instantiate ZXing integration class
                            xzing.IntentIntegrator scanIntegrator = new xzing.IntentIntegrator(this);
                            //start scanning
                            scanIntegrator.initiateScan();
                            return true;
                     }
                     catch (Exception e) {
                                  // TODO: handle exception
                           }
                    
        }
              return false;
    }
       public String getRealPathFromURI(Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
       protected void onActivityResult(int requestCode, int resultCode, Intent data) {
              Uri selectedImageUri = null;
              String filePath = null;
             
              Log.e("reqcode",""+ requestCode+""+resultCode);
              if (requestCode == 0) {
                     Toast toast1 = Toast.makeText(getApplicationContext(),
                                  requestCode, Toast.LENGTH_SHORT);
                     toast1.show();
                    
                  if (resultCode == RESULT_OK) {
                     Toast toast = Toast.makeText(getApplicationContext(),
                                         requestCode, Toast.LENGTH_SHORT);
                           toast.show();
                     xzing.IntentResult scanningResult = xzing.IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
                           //check we have a valid result
                           if (scanningResult != null) {
                                  //get content from Intent Result
                                  String scanContent = scanningResult.getContents();
                                  scanningResult.getFormatName();
                                  //output to UI
                                  //formatTxt.setText("FORMAT: "+scanFormat);
                                  Toast toast3 = Toast.makeText(getApplicationContext(),
                                                scanContent, Toast.LENGTH_SHORT);
                                  toast3.show();
                                  docid.setText(scanContent, TextView.BufferType.EDITABLE);
                           }
                           else{
                                  //invalid scan data or scan canceled
                                  Toast toast2 = Toast.makeText(getApplicationContext(),
                                                "No scan data received!", Toast.LENGTH_SHORT);
                                  toast2.show();
                           }
                  } else if (resultCode == RESULT_CANCELED) {
                      // Handle cancel
                  }
              }
              switch (requestCode) {
             
                           case PICK_IMAGE:
                          
                                 
                                  if (requestCode == RESULT_LOAD_IMAGE) {
                                         //Log.e("res",""+ RESULT_OK);
                                  selectedImageUri = data.getData();
                                  imagepath=getRealPathFromURI(selectedImageUri);
                                         //String imagepath=getResources().getResourceName(R.id.ImageView);
                               // Log.v("selectedImagePath", selectedImageUri.toString()+imagepath);
                                  }
                                  break;
                           case PICK_Camera_IMAGE:
                                   if (resultCode == RESULT_OK) {
                                    //use imageUri here to access the image
                                   selectedImageUri = imageUri;
                                   imagepath=getRealPathFromURI(selectedImageUri);
                                   //Log.v("selectedImagePath", selectedImageUri.toString()+imagepath);
                                  
                               } else if (resultCode == RESULT_CANCELED) {
                                    Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
                                } else {
                                   Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
                                }
                                   break;
                           case PICK_Scan_Code:
                                 
                                   break;
                     }
             
                     if(selectedImageUri != null){
                                  try {
                                         // OI FILE Manager
                                         String filemanagerstring = selectedImageUri.getPath();
                    
                                         // MEDIA GALLERY
                                         String selectedImagePath = getPath(selectedImageUri);
                    
                                         if (selectedImagePath != null) {
                                                filePath = selectedImagePath;
                                         } else if (filemanagerstring != null) {
                                                filePath = filemanagerstring;
                                         } else {
                                                Toast.makeText(getApplicationContext(), "Unknown path",
                                                              Toast.LENGTH_LONG).show();
                                                Log.e("Bitmap", "Unknown path");
                                         }
                    
                                         if (filePath != null) {
                                                resize(filePath);
                                         } else {
                                                bitmap = null;
                                         }
                                  } catch (Exception e) {
                                         Toast.makeText(getApplicationContext(), "Internal error",
                                                       Toast.LENGTH_LONG).show();
                                         Log.e(e.getClass().getName(), e.getMessage(), e);
                                   }
                     }
      
       }

       class ImageGalleryTask extends AsyncTask<Void, Void, String> {
              int response=0;
              @Override
      
              protected String doInBackground(Void... unsued) {
                     response=UploadFile();
                          
                     return "Success";
                     // (null);
              }

              @Override
              protected void onProgressUpdate(Void... unsued) {

              }

              @Override
              protected void onPostExecute(String sResponse) {
                     try {
                           if (dialog.isShowing())
                                  dialog.dismiss();
                           if(response==200)
                                  {
                                  Toast.makeText(getApplicationContext(),"File Uploaded Successfully!",Toast.LENGTH_LONG).show();
                                  }
                                               
                     } catch (Exception e) {
                           Toast.makeText(getApplicationContext(),       e.getMessage(),Toast.LENGTH_LONG).show();
                           Log.e(e.getClass().getName(), e.getMessage(), e);
                     }
              }

       }

       public String getPath(Uri uri) {
              String[] projection = { MediaStore.Images.Media.DATA };
              Cursor cursor = managedQuery(uri, projection, null, null, null);
              if (cursor != null) {
                     // HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
                     // THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
                     int column_index = cursor
                                  .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                     cursor.moveToFirst();
                     return cursor.getString(column_index);
              } else
                     return null;
       }

      
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///
       /**
        *
        * Show Progress Dialog start here
        */
       @Override
       protected Dialog onCreateDialog(int id)
       {
              switch(id)
              {
              case progress_bar_type:
                     //setting progress bar properties
                     pDialog=new ProgressDialog(this);
                  pDialog.setMessage("In Progress......Please wait");
                  pDialog.setIndeterminate(false);
                  pDialog.setMax(100);
                  pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                  pDialog.setCancelable(true);
                  pDialog.show();
                  return pDialog;
                  default:
                     return null;
              }
       }
      
       /**
        * Update Progress Bar
        */
       protected void onProgressUpdate(String... progress)
       {
               /* setting progress percentage*/
           pDialog.setProgress(Integer.parseInt(progress[0]));
       }
       /**
        * Progress bar Update End Here
        */
       /**
        * A method to donload json data from Url start here
        */
       private String DownloadUrl(String strUrl) throws Exception
       {
              String data="";
              InputStream iStream=null;
              try
              {
                     URL url=new URL(strUrl);
                   // Creating an http connection to communicate with url
               HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

               // Connecting to url
               urlConnection.connect();
               
               int Lengthofdata=urlConnection.getContentLength();
               //Reading Data From Url
               iStream=urlConnection.getInputStream();
               BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
               StringBuffer sb=new StringBuffer();
              
               String line = "";
               long total = 0;
               while(  ( line = br.readLine())  != null){
                    
                      total += 1;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                      onProgressUpdate(""+(int)((total*100)/Lengthofdata));
                   
                     sb.append(line);
               }
              
               data = sb.toString();
              
               br.close();
              }
              catch(Exception e)
              {
                     Log.d("excption while downloading data from url", e.getMessage().toString());
              }
              finally
              {
                     iStream.close();
              }
              return data;
       }
      
       /**
        * Download data from Url End Here
        */
private class DownLoadTaskINReason extends AsyncTask<String, Integer, String>
{
String data=null;
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
showDialog(progress_bar_type);
}
protected String doInBackground(String... url)
{
try{
data = DownloadUrl(url[0]);

//System.out.print("Number Of Record"+data);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
@Override
protected void onPostExecute(String result) {

DownloadWebSOReasonTask task = new DownloadWebSOReasonTask();
task.execute(result);

// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);

}
}
//to get Reason
private class DownloadWebSOReasonTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String response = "";
JSONObject jObject = null;

try
{
jObject=new JSONObject(urls[0]);

Reasonparser rep =new Reasonparser();
rep.ndreasonparse(jObject);

JSONArray jsonArray = new JSONArray(jObject.optString("Reason"));
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);

Log.v("Value Of K",k+"");
       if (k==1)
       {
        INReasonItems.add(jsonObject.optString("Description"));
       }
       else if(k==2)
       {
              OUTReasonItems.add(jsonObject.optString("Description"));
       }
       else if(k==3)
       {
              SKUReasonItems.add(jsonObject.optString("Description"));
       }

}

}
catch(Exception e)
{
Log.d("Error while parsing Data", e.toString());
}

return response;
}

@Override
protected void onPostExecute(String result) {
      
       if(k==1){
              dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
              spinner.setAdapter(dataAdapter);
       }else if(k==2)
       {
               dataAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
         spinner.setAdapter(dataAdapter1);
       }
       else if(k==3)
       {
               dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
         spinner.setAdapter(dataAdapter2);
       }
}
}

@Override
public void onItemSelected(AdapterView<?> parent, View arg1, int position, long arg3) {
       // TODO Auto-generated method stub
       String item = parent.getItemAtPosition(position).toString();
        Log.e("Here", "Here");
    // Showing selected spinner item
    Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();

}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
       // TODO Auto-generated method stub
       Log.e("Here", "dfdfdgdgfgHere");
}
private void resize(String path){
       // create the options
           BitmapFactory.Options opts = new BitmapFactory.Options();
           long length = path.length();
       //just decode the file
           opts.inJustDecodeBounds = true;
          BitmapFactory.decodeFile(path, opts);

       //get the original size
           int orignalHeight = opts.outHeight;
           int orignalWidth = opts.outWidth;
          
           Log.e("HeightWidth",""+orignalHeight +""+orignalWidth+"Le"+length);
       //initialization of the scale
           int resizeScale = 1;
       //get the good scale
           if ( orignalWidth > maxWidth || orignalHeight > maxHeight ) {
              final int heightRatio = Math.round((float) orignalHeight / (float) maxHeight);
              final int widthRatio = Math.round((float) orignalWidth / (float) maxWidth);
              resizeScale = heightRatio < widthRatio ? heightRatio : widthRatio;
           }
       //put the scale instruction (1 -> scale to (1/1); 8-> scale to 1/8)
           opts.inSampleSize = resizeScale;
           opts.inJustDecodeBounds = false;
       //get the futur size of the bitmap
           int bmSize = (orignalWidth / resizeScale) * (orignalHeight / resizeScale) * 4;
        
       //check if it's possible to store into the vm java the picture
           if ( Runtime.getRuntime().freeMemory() > bmSize ) {
       //decode the file
              bitmap = BitmapFactory.decodeFile(path, opts);
             
              ByteArrayOutputStream stream = new ByteArrayOutputStream();  
               bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);  
               byte[] imageInByte = stream.toByteArray();
               long lengthbmp = imageInByte.length;
               Log.e("AfterResize",lengthbmp+"");
              imgView.setImageBitmap(bitmap);
           }

       }
}

4>  Now move to our activity which send HTTP Post request and Upload image HttpFileUpload.java


import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.util.Log;

public class HttpFileUpload implements Runnable {
                                                 URL connectURL;
    String responseString;
  //  String Title;
    String Description;
    String FileName;
    String FolderName;
    String CustomerName;
    String UploadType;
    byte[ ] dataToServer;
    FileInputStream fileInputStream = null;
   
    public HttpFileUpload(String urlString, String vFolderName, String vDesc, String vFileName , String CustName,String Utype){
        try{
                connectURL = new URL(urlString);
                FolderName= vFolderName;
                Description = vDesc;
                FileName=vFileName;
                CustomerName=CustName;
                UploadType=Utype;
                Log.e("Desc", vDesc);
        }catch(Exception ex){
            Log.i("HttpFileUpload","URL Malformatted");
        }
}

public int Send_Now(FileInputStream fStream){
        fileInputStream = fStream;
     int i=   Sending();
                                                 return i;
}


public int Sending(){
                                                     int serverResponseCode =0;
        String iFileName = "000011.jpg";
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        String Tag="fSnd";
        try
        {
                Log.e(Tag,"Starting Http File Sending to URL");

                // Open a HTTP connection to the URL
                HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();

                // Allow Inputs
                conn.setDoInput(true);

                // Allow Outputs
                conn.setDoOutput(true);

                // Don't use a cached copy.
                conn.setUseCaches(false);

                // Use a post method.
                conn.setRequestMethod("POST");

                conn.setRequestProperty("Connection", "Keep-Alive");

                conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

                DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"filename\""+ lineEnd);
                dos.writeBytes(lineEnd);
                dos.writeBytes(Description);
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + lineEnd);
               
                dos.writeBytes("Content-Disposition: form-data; name=\"foldername\""+ lineEnd);
                dos.writeBytes(lineEnd);
                dos.writeBytes(FolderName);
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + lineEnd);
               
                dos.writeBytes("Content-Disposition: form-data; name=\"customername\""+ lineEnd);
                dos.writeBytes(lineEnd);
                dos.writeBytes(CustomerName);
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + lineEnd);
                   
                dos.writeBytes("Content-Disposition: form-data; name=\"uploadtype\""+ lineEnd);
                dos.writeBytes(lineEnd);
                dos.writeBytes(UploadType);
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + lineEnd);
                
                dos.writeBytes("Content-Disposition: form-data; name=\"fname\""+ lineEnd);
                dos.writeBytes(lineEnd);
                dos.writeBytes(FileName);
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + lineEnd);
               
                dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + iFileName +"\"" + lineEnd);
                dos.writeBytes(lineEnd);

                Log.e(Tag,"Headers are written");
                // create a buffer of maximum size
                int bytesAvailable = fileInputStream.available();
                   
                int maxBufferSize = 1 * 1024 * 1024;
                int bufferSize = Math.min(bytesAvailable, maxBufferSize);
                byte[ ] buffer = new byte[bufferSize];

                // read file and write it into form...
                int bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                while (bytesRead > 0)
                {
                        dos.write(buffer, 0, bufferSize);
                        bytesAvailable = fileInputStream.available();
                        bufferSize = Math.min(bytesAvailable,maxBufferSize);
                        bytesRead = fileInputStream.read(buffer, 0,bufferSize);
                }
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

           
               serverResponseCode = conn.getResponseCode();
                String serverResponseMessage = conn.getResponseMessage();
                if(serverResponseCode==200)
                 {

                 }
                System.out.println(serverResponseCode+serverResponseMessage);

                fileInputStream.close();
                dos.flush();
                dos.close();
                                                 return serverResponseCode;
        }
        catch (MalformedURLException ex)
        {
                                                
                Log.e(Tag, "URL error: " + ex.getMessage(), ex);
        }

        catch (IOException ioe)
        {
                Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
        }
        return serverResponseCode;
}

@Override
public void run() {
        // TODO Auto-generated method stub
}
}



Thank you please be open to give your suggestionJ

Comments

Popular posts from this blog

PHP Code to Connect Mysql Database

Php mysql connectivity code............. Write below code in connect.php file <?Php ob_start(); $host="localhost:3307"; // Host name $username="root"; // Mysql username $password="sa"; // Mysql password $db_name="dbname"; // Database name $tbl_name="login"; // Table name ?> include your connect file in page include ("config.php"); mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); execute your query $quer2=mysql_query("SELECT * FROM village"); $noticia2 = mysql_fetch_array($quer2); and that's it ..... www.indbricks.com

Android App To Send Free Message.

Android App To Send Free Message. Hi Friends I Have developed Android app to send Free Message from your Mobile . Now I have developed with only one provider "Way2Sms" . So Download from this link  http://www.exlvis.com/ FreeSmsandroid.aspx   and chk it out and give your Feedback So We can Customize and after we provide with All Providers. http://www.exlvis.com/ FreeSmsandroid.aspx Thanks Rajmal Kulmi Exlvis  Solutions Pvt. Ltd.