Monday, 8 July 2013

Android Inser to database

Helper.java

package com.example.feedback;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class Helper extends SQLiteOpenHelper{
    // database variables.
        //instead of com.mmad.irctc you have to write your own package name.
        private static String DB_PATH = "/data/data/com.example.feedback/databases/";
       
        //database name with sqllite extension
        private static String DB_NAME = "feedback.sqlite";
        private SQLiteDatabase myDataBase;
        private final Context myContext;
        private String TAG = "Helper";
        Cursor cursorGetData;
        SQLiteDatabase checkDB = null;

        public Helper(Context context) {
            super(context, DB_NAME, null, 1);
            this.myContext = context;
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        }

        public void createDataBase() throws IOException {

            boolean dbExist = checkDataBase();
            if (!dbExist) {
                this.getReadableDatabase();
                try {
                    copyDataBase();
                } catch (IOException e) {
                    throw new Error("Error copying database");
                }
            }
        }

        private boolean checkDataBase() {
            try {
                String myPath = DB_PATH + DB_NAME;
                checkDB = SQLiteDatabase.openDatabase(myPath, null,SQLiteDatabase.OPEN_READWRITE);
            } catch (SQLiteException e) {
                Log.e(TAG, "Error is" + e.toString());
            }
            if (checkDB != null) {
                checkDB.close();
            }
            return checkDB != null ? true : false;
        }

        private void copyDataBase() throws IOException {
            InputStream myInput = myContext.getAssets().open(DB_NAME);
            String outFileName = DB_PATH + DB_NAME;
            OutputStream myOutput = new FileOutputStream(outFileName);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0) {
                myOutput.write(buffer, 0, length);
            }
            myOutput.flush();
            myOutput.close();
            myInput.close();
        }

        public void openDataBase() throws SQLException {
            String myPath = DB_PATH + DB_NAME;
            myDataBase = SQLiteDatabase.openDatabase(myPath, null,SQLiteDatabase.OPEN_READWRITE);
        }

        public synchronized void close() {
            if (myDataBase != null)
                myDataBase.close();
            super.close();
        }

        private Cursor getData(String sql) {
            openDataBase();
            cursorGetData = getReadableDatabase().rawQuery(sql, null);
            return cursorGetData;
        }

        private long insertData(String tableName, ContentValues values) {
            openDataBase();
            return myDataBase.insert(tableName, null, values);

        }

        private int updateData(String tableName, ContentValues values,String condition) {
            openDataBase();
            return myDataBase.update(tableName, values, condition, null);
        }

        private int deleteData(String tableName, String condition) {
           
            return myDataBase.delete(tableName, condition, null);
        }

        //Select from the database        
        public List<CustomerInformationBeen> getGRCInfo() {
           
            ArrayList<CustomerInformationBeen> cList=new ArrayList<CustomerInformationBeen>();           
            try {
               
                String sql="Select * from customer_registration";
                Cursor cursor=getData(sql);
                int size = cursor.getCount();
                cursor.moveToFirst();
                for(int i=0;i<size;i++){
                    CustomerInformationBeen ci=new CustomerInformationBeen();
                    ci.setID(cursor.getInt(cursor.getColumnIndex("cr_id")));
                    ci.setName(cursor.getString(cursor.getColumnIndex("cr_name")));
                    ci.setAddress(cursor.getString(cursor.getColumnIndex("cr_address")));
                    ci.setCity(cursor.getString(cursor.getColumnIndex("cr_city")));
                    ci.setState(cursor.getString(cursor.getColumnIndex("cr_state")));
                    ci.setCountry(cursor.getString(cursor.getColumnIndex("cr_country")));
                    ci.setPin(cursor.getString(cursor.getColumnIndex("cr_pin")));
                    ci.setNationality(cursor.getString(cursor.getColumnIndex("cr_nationality")));
                    ci.setSex(cursor.getString(cursor.getColumnIndex("cr_sex")));
                    ci.setAge(cursor.getInt(cursor.getColumnIndex("cr_age")));
                    ci.setCompany(cursor.getString(cursor.getColumnIndex("cr_company")));
                    ci.setMobile(cursor.getString(cursor.getColumnIndex("cr_mobile")));
                    ci.setPhone(cursor.getString(cursor.getColumnIndex("cr_phone")));
                    ci.setEmail(cursor.getString(cursor.getColumnIndex("cr_email")));
                    ci.setDob(cursor.getString(cursor.getColumnIndex("cr_dob")));
                    ci.setDoa(cursor.getString(cursor.getColumnIndex("cr_doa")));
                    cList.add(ci);
                    cursor.moveToNext();
                }
                cursor.close();
                cursorGetData.close();
                myDataBase.close();
            } catch (Exception e) {
                // TODO: handle exception
            }           
            return cList;           
        }
       
        //getting selected data
        public Map<Integer, String>  getSelectedCusInfo(int id) {
           
            Map<Integer, String> sMap = new HashMap<Integer, String>();
           
            try {
                String sql="Select * from customer_registration  where cr_id="+id;
                Cursor cursor=getData(sql);
                int size = cursor.getCount();
                cursor.moveToFirst();
                for(int i=0;i<size;i++){
                    sMap.put(1,cursor.getString(cursor.getColumnIndex("cr_name")));
                    sMap.put(2,cursor.getString(cursor.getColumnIndex("cr_address")));
                    sMap.put(3,cursor.getString(cursor.getColumnIndex("cr_city")));
                    sMap.put(4,cursor.getString(cursor.getColumnIndex("cr_state")));
                    sMap.put(5,cursor.getString(cursor.getColumnIndex("cr_country")));
                    sMap.put(6,cursor.getString(cursor.getColumnIndex("cr_pin")));
                    sMap.put(7,cursor.getString(cursor.getColumnIndex("cr_nationality")));
                    sMap.put(8,cursor.getString(cursor.getColumnIndex("cr_sex")));
                    sMap.put(9,cursor.getString(cursor.getColumnIndex("cr_age")));
                    sMap.put(10,cursor.getString(cursor.getColumnIndex("cr_company")));
                    sMap.put(11,cursor.getString(cursor.getColumnIndex("cr_mobile")));
                    sMap.put(12,cursor.getString(cursor.getColumnIndex("cr_phone")));
                    sMap.put(13,cursor.getString(cursor.getColumnIndex("cr_email")));
                    sMap.put(14,cursor.getString(cursor.getColumnIndex("cr_dob")));
                    sMap.put(15,cursor.getString(cursor.getColumnIndex("cr_doa")));
                }
            } catch (Exception e) {
                // TODO: handle exception
            }
           
            return sMap;
           
        }
       
      
        /*
          //Select from database
          public ArrayList<UserContacts> getContactAdult() {
            ArrayList<UserContacts> passengerInfo = new ArrayList<UserContacts>();
            try {
                Cursor cursor = getData("select * from Contacts where C_Age>4");
                int size = cursor.getCount();
                cursor.moveToFirst();
                for (int i = 0; i < cursor.getCount(); i++) {
                    UserContacts contact=new UserContacts();
                    contact.setContactID(cursor.getString(cursor.getColumnIndex("C_ID")));
                    contact.setContactName(cursor.getString(cursor.getColumnIndex("C_Name")));
                    contact.setContactAge(cursor.getInt(cursor.getColumnIndex("C_Age")));
                    contact.setContactDOB(cursor.getString(cursor.getColumnIndex("C_DOB")));
                    contact.setContactGender(cursor.getString(cursor.getColumnIndex("C_Gender")));
                    contact.setContactGCode(cursor.getString(cursor.getColumnIndex("C_GCode")));
                    contact.setContactFoodPref(cursor.getString(cursor.getColumnIndex("C_FoodPref")));
                    contact.setContactFPCode(cursor.getString(cursor.getColumnIndex("C_FPCode")));
                    contact.setContactIDCardType(cursor.getString(cursor.getColumnIndex("C_IDCardType")));
                    contact.setContactIDCCode(cursor.getString(cursor.getColumnIndex("C_IDCCode")));
                    contact.setContactIDCardNo(cursor.getString(cursor.getColumnIndex("C_IDCardNo")));
                    contact.setContactSeniorCitizen(cursor.getString(cursor.getColumnIndex("C_SenoirCitizen")));
                    contact.setContactFlag(cursor.getString(cursor.getColumnIndex("C_flag")));
                    passengerInfo.add(contact);
                    cursor.moveToNext();
                }
               
                cursor.close();
                cursorGetData.close();
                myDataBase.close();
       
            } catch (Exception ex) {
       
            }
            return passengerInfo;
          }
          */
        /*
            //Update the database
            public long updateChildPassenger(String childID, UserContacts usercontact) {
            long value = 0;
            try
            {
                 ContentValues initialValues = new ContentValues();
                 SQLiteDatabase db=this.getWritableDatabase();
                 openDataBase();
                  initialValues.put("tc_Name",usercontact.getContactName());
                  initialValues.put("tc_Gender",usercontact.getContactGender());
                initialValues.put("tc_Age",usercontact.getContactAge());
                initialValues.put("tc_DOB",usercontact.getContactDOB());
                initialValues.put("C_ID",new RandomNumber().GenerateRandomNumber());
                value = db.update("temp_child", initialValues, "tc_Id="+childID, null);
                myDataBase.close();
            }
                catch (Exception e) {
                   
                    Log.e("error is",""+e);
                   
                }
            return value;
           
        }
*/
       
        //delete the database
        public int deleteAdultContact(String contactID) {
            int value = 0;
            try {
                openDataBase();
                value = deleteData("temp_adult","ta_Id ="+contactID);
                myDataBase.close();
            } catch (Exception ex) {
                Log.d(TAG, "Error in deleteAdultContact()" + ex.toString());
            }
            return value;
        }

        public long insertUser(String name, String address,String city,String state,String country,String pin,String nationality,String sex,String age,String company,String mobile,String phone,String email,String dob,String doa) {
            long value = 0;
            try {
               
                ContentValues initialValues = new ContentValues();
               
                initialValues.put("cr_name", name);
                initialValues.put("cr_address", address);
                initialValues.put("cr_city", city);
                initialValues.put("cr_state", state);
                initialValues.put("cr_country", country);
                initialValues.put("cr_pin", pin);
                initialValues.put("cr_nationality", nationality);
                initialValues.put("cr_sex", sex);
                initialValues.put("cr_age", age);
                initialValues.put("cr_company", company);
                initialValues.put("cr_mobile", mobile);
                initialValues.put("cr_phone", phone);
                initialValues.put("cr_email", email);
                initialValues.put("cr_dob", dob);
                initialValues.put("cr_doa", doa);
               
                value = insertData("customer_registration", initialValues);
                Log.d("value1=", "" + value);

            }catch (Exception e) {
                // TODO: handle exception
            }
            return value;
           
        }

       
    }



activity



for insert call the method


long value = helper.insertUser(nameValue,address.getText().toString(),city.getText().toString(),state.getText().toString(),country.getText().toString(),pin.getText().toString(),nationality.getText().toString(),sex.getText().toString(),age.getText().toString(),company.getText().toString(),mobile.getText().toString(),phone.getText().toString(),email.getText().toString(),dob.getText().toString(),doa.getText().toString());
                    Log.d("Value","Inserted = "+value);


for display



List<CustomerInformationBeen> list=new ArrayList<CustomerInformationBeen>();
            list=helper.getGRCInfo();
            Iterator<CustomerInformationBeen> itr=list.iterator();
            while (itr.hasNext()) {
                CustomerInformationBeen ci =  itr.next();
                int cusID=ci.getID();
                String cname=ci.getName();
               
                //creating dynamic textview
                TextView cnameText=new TextView(this);
                cnameText.setText(cname);
                cnameText.setId(cusID);
                cusListinfo.addView(cnameText);

}



using map


Map<Integer, String> sMap=new HashMap<Integer, String>();
                        sMap=helper.getSelectedCusInfo(id);
                       
                        name.setText(sMap.get(1));



How can I remove a button or make it invisible in Android?

To remove button in java code:
Button btn=(Button)findViewById(R.id.btn);
btn.setVisibility(View.GONE);
To transparent Button in java code:
Button btn=(Button)findViewById(R.id.btn);
btn.setVisibility(View.INVISIBLE);
To remove button in Xml file:
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"/>
To transparent button in Xml file:
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"/>

Saturday, 6 July 2013

android: how todivide linear layout elements equally

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

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:enabled="false"
        android:text="Installed engines" >
    </Button>

    <ListView
        android:id="@+id/primary"
        android:layout_width="match_parent"
        android:layout_height="0dp" 
        android:layout_weight="1" >
    </ListView>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:enabled="false"
        android:text="Active engines" >
    </Button>

    <ListView
        android:id="@+id/secondary"
        android:layout_width="match_parent"
        android:layout_height="0dp" 
        android:layout_weight="1" >
    </ListView>

</LinearLayout>

Upload from SD card to server

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
  
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/title_direct"
    android:layout_marginBottom="6px"
    />

 <Button
    android:id="@+id/button_upload_files_id"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Upload files from SDCard to SMB server"
    />

 <Button
    android:id="@+id/button_download_files_id"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Download files from SMB server to SDCard"
    />
  
 <Button
    android:id="@+id/button_upload_folder_id"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Upload folder from SDCard to SMB server"
    />         

 <Button
    android:id="@+id/button_download_folder_id"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Download folder from SMB server to SDCard"
    />
  
 <Button
    android:id="@+id/button_download_file_alias_id"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Download file from SMB server through alias"
    />
 
 <Button
    android:id="@+id/button_explorer_id"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Browse SMB server"
    /> 
      
 <Button
    android:id="@+id/button_share_id"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Share from gallery to SMB"
    />
        
</LinearLayout>





package test.andsmbclient;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity
{
    private static final String TAG = MainActivity.class.getName();
    private static final int UPLOAD_FILES_REQUEST = 0;
    private static final int DOWNLOAD_FILES_REQUEST = 1;
    private static final int UPLOAD_FOLDER_REQUEST = 2;
    private static final int DOWNLOAD_FOLDER_REQUEST = 3;
    private static final int DOWNLOAD_FILE_ALIAS_REQUEST = 4;
    private static final int BROWSE_REQUEST = 5;
    private static final int SEND_REQUEST = 6;
   
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        // Upload files sample
        Button uploadFilesButton = (Button) findViewById(R.id.button_upload_files_id);
        uploadFilesButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_PICK);
                // SMB URL (Starts smb:// followed by hostname and port).
                Uri smbUri = Uri.parse("smb://192.168.20.128");
                intent.setDataAndType(smbUri, "vnd.android.cursor.dir/lysesoft.andsmb.uri");
                // Upload
                intent.putExtra("command_type", "upload");
                // SMB credentials (optional)
                intent.putExtra("smb_username", "guest");
                //intent.putExtra("smb_password", "yourpassword");
                //intent.putExtra("smb_domain", "YOURDOMAIN");
                // SMB settings (optional)
                //intent.putExtra("smb_encoding", "UTF-8");
                // Activity title
                intent.putExtra("progress_title", "Uploading files ...");
                intent.putExtra("local_file1", "/sdcard/subfolder1/file1.zip");
                intent.putExtra("local_file2", "/sdcard/subfolder2/file2.zip");
                // Optional initial remote folder (it must exist before upload)
                intent.putExtra("remote_folder", "/remotefolder/subfolder");
                //intent.putExtra("close_ui", "true");
                startActivityForResult(intent, UPLOAD_FILES_REQUEST);
            }
        });
               
        // Download files sample.
        Button downloadFilesButton = (Button) findViewById(R.id.button_download_files_id);
        downloadFilesButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_PICK);
                // SMB URL (Starts smb:// followed by hostname and port).
                Uri smbUri = Uri.parse("smb://192.168.20.128");
                intent.setDataAndType(smbUri, "vnd.android.cursor.dir/lysesoft.andsmb.uri");
                // Download
                intent.putExtra("command_type", "download");
                // SMB credentials (optional)
                intent.putExtra("smb_username", "guest");
                //intent.putExtra("smb_password", "yourpassword");
                //intent.putExtra("smb_domain", "YOURDOMAIN");
                // SMB settings (optional)
                //intent.putExtra("smb_encoding", "UTF-8");
                // Activity title
                intent.putExtra("progress_title", "Downloading files ...");
                // Remote files to download.
                intent.putExtra("remote_file1", "/remotefolder/subfolder/file1.zip");
                intent.putExtra("remote_file2", "/remotefolder/subfolder/file2.zip");
                // Target local folder where files will be downloaded.
                intent.putExtra("local_folder", "/sdcard/localfolder");   
                intent.putExtra("close_ui", "true");   
                startActivityForResult(intent, DOWNLOAD_FILES_REQUEST);
            }
        });
       
        // Upload folder sample.
        Button uploadFolderButton = (Button) findViewById(R.id.button_upload_folder_id);
        uploadFolderButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_PICK);
                // SMB URL (Starts smb:// followed by hostname and port).
                Uri smbUri = Uri.parse("smb://192.168.20.128");
                intent.setDataAndType(smbUri, "vnd.android.cursor.dir/lysesoft.andsmb.uri");
                // SMB credentials (optional)
                intent.putExtra("smb_username", "guest");
                //intent.putExtra("smb_password", "yourpassword");
                //intent.putExtra("smb_domain", "YOURDOMAIN");
                // SMB settings (optional)
                //intent.putExtra("smb_encoding", "UTF-8");
                // Upload
                intent.putExtra("command_type", "upload");
                // Activity title
                intent.putExtra("progress_title", "Uploading folder ...");
                intent.putExtra("local_file1", "/sdcard/localfolder");
                // Optional initial remote folder (it must exist before upload)
                intent.putExtra("remote_folder", "/remotefolder/uploadedfolder");
                startActivityForResult(intent, UPLOAD_FOLDER_REQUEST);
            }
        });     
       
        // Download full folder
        Button downloadFolderButton = (Button) findViewById(R.id.button_download_folder_id);
        downloadFolderButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_PICK);
                // SMB URL (Starts smb:// followed by hostname and port).
                Uri smbUri = Uri.parse("smb://192.168.20.128");
                intent.setDataAndType(smbUri, "vnd.android.cursor.dir/lysesoft.andsmb.uri");
                // SMB credentials (optional)
                intent.putExtra("smb_username", "guest");
                //intent.putExtra("smb_password", "yourpassword");
                //intent.putExtra("smb_domain", "YOURDOMAIN");
                // SMB settings (optional)
                //intent.putExtra("smb_encoding", "UTF-8");   
                // Download
                intent.putExtra("command_type", "download");
                // Activity title
                intent.putExtra("progress_title", "Downloading folder ...");
                // Remote folder to download (must not end with /).
                intent.putExtra("remote_file1", "/remotefolder/uploadedfolder");
                intent.putExtra("local_folder", "/sdcard/downloadedfolder");           
                startActivityForResult(intent, DOWNLOAD_FOLDER_REQUEST);
            }
        });
       
        // Pass alias matching to SMB configuration in AndSMB.
        Button downloadFileAliasButton = (Button) findViewById(R.id.button_download_file_alias_id);
        downloadFileAliasButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_PICK);
                Uri smbUri = Uri.parse("alias://myandsmbalias");
                intent.setDataAndType(smbUri, "vnd.android.cursor.dir/lysesoft.andsmb.uri");
                intent.putExtra("command_type", "download");
                intent.putExtra("remote_file1", "/remotefolder/subfolder/file1.zip");
                intent.putExtra("local_folder", "/sdcard/downloadedfolderalias");   
                startActivityForResult(intent, DOWNLOAD_FILE_ALIAS_REQUEST);
            }
        });   


        // Browse SMB server.
        Button explorerButton = (Button) findViewById(R.id.button_explorer_id);
        explorerButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                Uri smbUri = Uri.parse("smb://192.168.20.128:445");
                intent.setData(smbUri);
                intent.putExtra("smb_username", "guest");
                //intent.putExtra("smb_password", "yourpassword");
                //intent.putExtra("smb_domain", "YOURDOMAIN");
                // Optional share and/or remote folder.
                //intent.putExtra("remote_folder", "/yourshare/subfolder");
                startActivityForResult(intent, BROWSE_REQUEST);
            }
        });     
       
        // Share (upload) from gallery.
        Button shareButton = (Button) findViewById(R.id.button_share_id);
        shareButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_SEND);
                intent.setType("image/jpeg");
                intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://media/external/images/media/103"));
                startActivityForResult(intent, SEND_REQUEST);
            }
        });  
    }


    protected void onActivityResult(int requestCode, int resultCode, Intent intent)
    {
        Log.i(TAG, "Result: "+resultCode+ " from request: "+requestCode);
        if (intent != null)
        {
            String transferredBytesStr = intent.getStringExtra("TRANSFERSIZE");
            String transferTimeStr = intent.getStringExtra("TRANSFERTIME");
            Log.i(TAG, "Transfer status: " + intent.getStringExtra("TRANSFERSTATUS"));
            Log.i(TAG, "Transfer amount: " + intent.getStringExtra("TRANSFERAMOUNT") + " file(s)");
            Log.i(TAG, "Transfer size: " + transferredBytesStr + " bytes");
            Log.i(TAG, "Transfer time: " + transferTimeStr + " milliseconds");
            // Compute transfer rate.
            if ((transferredBytesStr != null) && (transferTimeStr != null))
            {
                try
                {
                    long transferredBytes = Long.parseLong(transferredBytesStr);
                    long transferTime = Long.parseLong(transferTimeStr);
                    double transferRate = 0.0;
                    if (transferTime > 0) transferRate = ((transferredBytes) * 1000.0) / (transferTime * 1024.0);
                    Log.i(TAG, "Transfer rate: " + transferRate + " KB/s");
                }
                catch (NumberFormatException e)
                {
                    // Cannot parse string.
                }
            }
        }
    }
   
}

Friday, 5 July 2013

Android Upload Video in server

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text=""
    android:id="@+id/tv"
    />
    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
<Button android:text="Browse gallery"
    android:id="@+id/Button01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
</Button>
<ImageView android:id="@+id/ImageView01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
</ImageView>
</LinearLayout>


uploadfile.java

public class uploadfile extends Activity {
    TextView tv = null;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView) findViewById(R.id.tv);
        doFileUpload();
    }
   
    private void doFileUpload(){

          HttpURLConnection conn = null;
          DataOutputStream dos = null;
          DataInputStream inStream = null;

       
          String exsistingFileName = "/sdcard/six.3gp";
          // Is this the place are you doing something wrong.

          String lineEnd = "\r\n";
          String twoHyphens = "--";
          String boundary =  "*****";


          int bytesRead, bytesAvailable, bufferSize;

          byte[] buffer;

          int maxBufferSize = 1*1024*1024;
 
          String urlString = "http://192.168.1.5/upload.php";
         
         
         
          try
          {
          
       
          Log.e("MediaPlayer","Inside second Method");

          FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName) );



           URL url = new URL(urlString);

           conn = (HttpURLConnection) url.openConnection();

           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);

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

           dos.writeBytes(twoHyphens + boundary + lineEnd);
           dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + exsistingFileName +"\"" + lineEnd);
           dos.writeBytes(lineEnd);

           Log.e("MediaPlayer","Headers are written");



           bytesAvailable = fileInputStream.available();
           bufferSize = Math.min(bytesAvailable, maxBufferSize);
           buffer = new byte[bufferSize];



           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);

           BufferedReader in = new BufferedReader(
                           new InputStreamReader(
                           conn.getInputStream()));
                String inputLine;
               
                while ((inputLine = in.readLine()) != null)
                    tv.append(inputLine);

          
          
          
           // close streams
           Log.e("MediaPlayer","File is written");
           fileInputStream.close();
           dos.flush();
           dos.close();


          }
          catch (MalformedURLException ex)
          {
               Log.e("MediaPlayer", "error: " + ex.getMessage(), ex);
          }

          catch (IOException ioe)
          {
               Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe);
          }


          //------------------ read the SERVER RESPONSE


          try {
                inStream = new DataInputStream ( conn.getInputStream() );
                String str;
              
                while (( str = inStream.readLine()) != null)
                {
                     Log.e("MediaPlayer","Server Response"+str);
                }
                /*while((str = inStream.readLine()) !=null ){
                   
                }*/
                inStream.close();

          }
          catch (IOException ioex){
               Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
          }
         
         

        }
}

AndroidManifest.xml

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

upload.php

<?php

move_uploaded_file($_FILES['uploadedfile']['tmp_name'], "./".$_FILES["uploadedfile"]["name"]);

?>