Wednesday 9 September 2015

Upload Large video file from android device using PHP.

           
              Sharing files has always been one of Android's greatest strengths. A system of "share intents" allow apps to freely exchange data with each other, making it possible to take a picture with your favorite camera app, then send it over to your choice of photo-sharing apps, for instance.

              Even with a wide variety of cloud-based services that are easily accessible through Android's Share functionality, sending actual video files to your friends is still generally a convoluted process.


              Many cloud services have restrictive file size limits, and videos are among the biggest files out there.Without that hurdle in the way, the act of sharing an large file is still an issue.

Now i am describing the android code how to upload the large video file

make one new function

private String uploadVideo(String videoPath) throws ParseException, IOException();


private String uploadVideo(String videoPath) throws ParseException, IOException {
       HttpClient httpclient = new DefaultHttpClient();
                                             httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
      
        //hear mansion the URL of your PHP service
        HttpPost httppost = new HttpPost("https://xyx.com/uploadmedia.php");
      
        //FileBody filebodyVideo = new FileBody(new File(videoPath)); //this is also for add file content

        //add file path of your local directory like from sdcard
        ContentBody fileBody=new FileBody(new File(videoPath));
      
        //other paramiter title of the video
        StringBody title = new StringBody( "Title of the video");
        //any description you want to add
        StringBody description = new StringBody("This is a video of the agent");

        //for the progress that how much video had been uploaded
        AndroidMultiPartEntity reqEntity = new AndroidMultiPartEntity(
                new ProgressListener() {

                    @Override
                    public void transferred(long num) {
                        publishProgress((int) ((num / (float) totalSize) * 100));
                    }
                });

        // add all part in to AndroidMultiPartEntity
        reqEntity.addPart("videoFile", fileBody);
        reqEntity.addPart("title", title);
        reqEntity.addPart("description", description);
        
        //set AndroidMultiPartEntity to HttpPost
        httppost.setEntity(reqEntity);
      
        //get total size of the part data. so we can calculate the uploading progress
        totalSize = reqEntity.getContentLength();

        // DEBUG
        System.out.println( "executing request " + httppost.getRequestLine( ) );
       
        //execut the request
        HttpResponse response = httpclient.execute( httppost );
        HttpEntity resEntity = response.getEntity( );
      
        // DEBUG
        System.out.println( response.getStatusLine( ) );
        if (resEntity != null) {
            System.out.println( EntityUtils.toString( resEntity ) );
        } // end if

        if (resEntity != null) {
            resEntity.consumeContent( );
        } // end if

        httpclient.getConnectionManager( ).shutdown( );
      
        return convertStreamToString(resEntity.getContent());
    } // end of uploadVideo( )

call this method in to asyc task



public class UploadLargeFileAsync extends AsyncTask<Void, Integer, String>{
    private long totalSize=0;
   
    private String mLocalSDCardFilePath;
   
    private ProgressDialog progressDialog;
   
    public UploadLargeFileAsync(Context context,String localSDCardfilePath) {
        mLocalSDCardFilePath=localSDCardfilePath;
       
        progressDialog=new ProgressDialog(context);
        progressDialog.show();
        progressDialog.setCancelable(false);
       
    }
   
    @Override
    protected String doInBackground(Void... params) {
       
        try {
            return uploadVideo(mLocalSDCardFilePath);
        } catch (Exception e) {
            return "";
        }
       
    }
   
   
    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        System.out.println("Uploading  "+values[0]+"%");
        progressDialog.setMessage("Uploading  "+values[0]+"%");
    }

   
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        progressDialog.cancel();
    }


public String convertStreamToString(InputStream is) throws IOException {
        if (is != null) {
            StringBuilder sb = new StringBuilder();
            String line;
            try {
                BufferedReader reader = new BufferedReader(    new InputStreamReader(is, "UTF-8"));
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
            } finally {
                is.close();
            }
            return sb.toString();
        } else {
            return "";
        }
    }

}




make a few code on php side in file http://xyz.com/uploadmedia.php

header('Content-type: multipart/form-data');
    echo "<pre>";
    print_r($_REQUEST);
    echo "hiiiii";
    var_dump($_FILE);
    echo $fileName = $_FILES['videoFile']['name']."<br>";
    echo $fileTempName = $_FILES['videoFile']['tmp_name']."<br>";
    echo $fileType = $_FILES['videoFile']['type']."<br>";
    echo $fileSize = $_FILES['videoFile']['size']."<br>";
    echo $fileError = $_FILES['videoFile']['error']."<br>";
    if(is_uploaded_file($_FILES['videoFile']['tmp_name'])) {
       
        $dest=  $_FILES['videoFile'] ['name'];
        move_uploaded_file ($_FILES['videoFile'] ['tmp_name'], "uploads/$dest);
    }
    else
    {
        echo "no file found";
    }


Monday 20 October 2014

Serializing and Deserializing a multiple Object

Serializing and Deserializing  a multiple Object


Make function to write multiple object in to one file

public void writeToBinary (String filename, Object obj, boolean append){
        File file = new File (filename);
        ObjectOutputStream out = null;

        try{
            if (!file.exists () || !append) out = new ObjectOutputStream (new FileOutputStream (filename));
            else out = new AppendableObjectOutputStream (new FileOutputStream (filename, append));
            out.writeObject(obj);
            out.flush ();
        }catch (Exception e){
            e.printStackTrace ();
        }finally{
            try{
                if (out != null) out.close ();
            }catch (Exception e){
                e.printStackTrace ();
            }
        }
    }

Class For Serialiable appending



private  class AppendableObjectOutputStream extends ObjectOutputStream {

        public AppendableObjectOutputStream(OutputStream out) throws IOException {

          super(out);

        }



        @Override

        protected void writeStreamHeader() throws IOException {}

  }



So now we are Serializing multiple object in to the file


public void Serlize() {
EmployeeInfo e = new EmployeeInfo();
e.name = "Appu Patel";
e.address = "At Valsad, Gujarat";
EmployeeInfo e1 = new EmployeeInfo();
e1.name = "Alpan";
e1.address = "At Surat, Gujarat";
EmployeeInfo e2 = new EmployeeInfo();
e2.name = "Rumit";
e2.address = "At Kadi,At Ghadhinagar";
EmployeeInfo e3 = new EmployeeInfo();
e3.name = "Prashant";
e3.address = "At Lilapor, Valsad Gujarat";
try {
FileOutputStream fileOut = new FileOutputStream(
"employee.ser");
writeToBinary("employee.ser", e, true);
writeToBinary("employee.ser", e1, true);
writeToBinary("employee.ser", e2, true);
writeToBinary("employee.ser", e3, true);
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/employee.bin");
} catch (IOException i) {
i.printStackTrace();
}
}

Deserializing multiple object from file


public ArrayList<EmployeeInfo> Deserialize() throws ClassNotFoundException {
      try{
       ArrayList<EmployeeInfo> employees=new ArrayList<EmployeeInfo>();
       EmployeeInfo o=null;
       ObjectInputStream in = new ObjectInputStream(new FileInputStream("employee.ser"));

         while (true) {
             try {
                  o = (EmployeeInfo) in.readObject();
                  
                  employees.add(o);
                 // Do something with the object
             } catch (EOFException ex) {
                 break;
             }
         }

         in.close();
      
          in.close();
       System.out.println(employees.size());

         return employees;
     // return employees;
      }catch(IOException i){
         i.printStackTrace();
         return null;
      }
}



All the Best

Object Serialization Deserialization java

TO store name, address,city detail and other person information are store in data base sqlite or any other database . but how we can store large size of image in to database. some of few data base structure can provide some data type but in sqlLite can provide this structure. so now i can display you that how we can store media file to store in to file.


Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.

The ObjectOutputStream class contains many write methods for writing various data types, but one method in particular stands out:

public final void writeObject(Object x) throws IOException

The above method serializes an Object and sends it to the output stream. Similarly, the ObjectInputStream class contains the following method for deserializing an object:

public final Object readObject() throws IOException,ClassNotFoundException

This method retrieves the next Object out of the stream and deserializes it. The return value is Object, so you will need to cast it to its appropriate data type.


To demonstrate how serialization works in Java, I am going to use the EmployeeInfo class. In Java We are calling as Plain Object.which implements the Serializable interface:


public class EmployeeInfo implements Serializable{
    public String name;
    public String address;
   public String getName() {
      return name;
   }
  public void setName(String name) {
     this.name = name;
  }
  public String getAddress() {
     return address;
  }
  public void setAddress(String address) {
    this.address = address;
  }
}



Notice that for a class to be serialized successfully, two conditions must be met:
  • The class must implement the java.io.Serializable interface.
  • All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient. 

Serializing an Object:

The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo program instantiates an EmployeeInfo object and serializes it to a file.

public class SerializeDemo{
   public static void main(String [] args){
      EmployeeInfo e = new EmployeeInfo ();
      e.name = "Alpan A Patel";
      e.address = "At Dived, Po Atul, Dist Valsad (Talav Dalia);
      try{
         FileOutputStream fileOut =  new FileOutputStream("/tmp/employee.bin");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
         fileOut.close();
         System.out.printf("Serialized data is saved in /tmp/employee.bin");//you can give any extension
      }catch(IOException i){
          i.printStackTrace();
      }
   }
}

Deserializing an Object:

The following DeserializeDemo program deserializes the Employee object created in the SerializeDemo program. Study the program and try to determine its output:

import java.io.*;
public class DeserializeDemo{
   public static void main(String [] args){
      Employee e = null;
      try{
         FileInputStream fileIn = new FileInputStream("/tmp/employee.bin");
         ObjectInputStream in = new ObjectInputStream(fileIn);
         e = (EmployeeInfo) in.readObject();
         in.close();
         fileIn.close();
      }catch(IOException i){
         i.printStackTrace();
         return;
      }catch(ClassNotFoundException c){
         System.out.println("EmployeeInfo class not found");
         c.printStackTrace();
         return;
      }
      System.out.println("Deserialized Employee...");
      System.out.println("Name: " + e.name);
      System.out.println("Address: " + e.address); 
    }
}

All the Best

Tuesday 14 October 2014

Send Mail Through Email Intent

In android While sending mail by Email intent You are using this code sample



Intent sendIntent=new Intent(); 
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT,"Hello World");
sendIntent.setType("text/plain"); 
//startActivity(sendIntent);
startActivity(Intent.createChooser(sendIntent,"Restaurant Share to"));

you can use multiple type for the send multiple content like 


intent.setType("*/*"); //for all
intent.setType("text/html"); // for HTML content
intent.setType("image/*");//for image
intent.setType("text/plain");// for only text


While You are using this code so many intents are open in to the android device that contain the send intent.

But you want to open a specific intent in to android device that is contain the send intent that is also possible by this code.

Example If You r sending only mail then Use this following code


// for default intent
Intent emailIntent = new Intent();
emailIntent.setAction(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_TEXT, "Hello World");
emailIntent.putExtra(Intent.EXTRA_EMAIL  , new String[]{"xyz@gmail.com"});
emailIntent.putExtra(Intent.EXTRA_SUBJECT,  "Subject Enter Here");
emailIntent.setType("message/rfc822");

// get the list of intent and get total information that contan the send intent
PackageManager pm = getActivity().getPackageManager();
Intent sendIntent = new Intent(Intent.ACTION_SEND);  
sendIntent.setType("text/plain");

// for display message while opening the
Intent openInChooser = Intent.createChooser(emailIntent,"Send email...");

// then get the list of resolve information object list from package manager
List<ResolveInfo> resInfo = pm.queryIntentActivities(sendIntent, 0);

        List<LabeledIntent> intentList = new ArrayList<LabeledIntent>();      

for (int i = 0; i < resInfo.size(); i++) {

// Extract the label, append it, and repackage it in a LabeledIntent
ResolveInfo ri = resInfo.get(i);
String packageName = ri.activityInfo.packageName;
/*is the mail client available the check the condition which is available in to the list                               object*/
                        if(packageName.contains("android.email")) {
emailIntent.setPackage(packageName);
} else if( packageName.contains("android.gm")) {
Intent intent = new Intent();
intent.setComponent(new ComponentName(packageName, i.activityInfo.name));
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT,"");
intent.putExtra(Intent.EXTRA_EMAIL  , new String[]{"xyz@gmail.com"});
intent.putExtra(Intent.EXTRA_SUBJECT, "Subject Enter here");                                 intent.setType("message/rfc822");
                                //add intent object in to the in to the lebeledIntent list
                                intentList.add(new LabeledIntent(intent, packageName, ri.loadLabel(pm), ri.icon));
}
}
                // convert intentList to array
LabeledIntent[] extraIntents = intentList.toArray( new LabeledIntent[ intentList.size() ]);
openInChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);
startActivity(openInChooser);

Tuesday 23 September 2014

TextView native Shadow Effect

 
In android not require to take extra resource to like image to make text view text have shadow effect. to make native effect to TextView follow this few lines of code


<TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
               

                android:shadowColor="#000000"                

                android:shadowDx="2"                

                android:shadowDy="2"                

                android:shadowRadius="2"                

                

                android:text="Your Text With Shadow"
                android:textColor="#FF0000"
                android:textSize="20sp" />


View Display like




Above highlighted line that is to make simple shadow effect to TextView. and make your application light weight and increase your performance

Wednesday 12 March 2014

Open specific URL in to Browser Intent

1)Take any URL that you want to open

   String url = "http://www.google.com";

2) create intent object 
android.content.Intent.Intent(String action)
Create an intent with a given action. All other fields (data, type, class) are null. Note that the action must be in a namespace because Intents are used globally in the system -- for example the system VIEW action is android.intent.action.VIEW;
Intent ACTION_VIEW

that is
   Intent i = new Intent(Intent.ACTION_VIEW);
3) from that intent object use this Intent android.content.Intent.setData(Uri data) method pass URI into them
   i.setData(Uri.parse(url));

4) And normaly start activity by passing that created intent
   startActivity(i);


GOOD LUCK

Monday 6 January 2014

Transparent Color in Android

To make any color as a transparent in android. 



Write in your resource file 
<color name="your_color_name">#CCE4D5FF</color>

your hex color code with RGB combination with 6 character 

but if you need to make transparency in to the color put 2 more character. 

To know follow the steps.

First go in to the Resource (res) folder 


Then go in to the value folder any xml file

Write this attribute 

<color name="your_color_name">#CCE4D5FF</color>

This red highlighted code is for hexa color 

To know hexa color please folow this link RGB color

And Yellow highlighted code is for transparency.

For more transparency by percentage. 

100% — FF

95% — F2

90% — E6

85% — D9

80% — CC

75% — BF

70% — B3

65% — A6

60% — 99

55% — 8C

50% — 80

45% — 73

40% — 66

35% — 59

30% — 4D

25% — 40

20% — 33

15% — 26

10% — 1A

5% — 0D

0% — 00


All The best........