Tuesday, April 23, 2013

Download a File In Android From Remote Server

Download a File In Android From Remote Server


In Your class file put add this code 


package com.facebook.samples.sessionlogin;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button; 


public class HTTPTest extends Activity {
String dwnload_file_path = "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc6/187259_10000060421658402_744490318028_q.jpg";
    String dest_file_path = "/sdcard/dwnloaded_file.png";
    Button b1;
    ProgressDialog dialog = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
         
        b1 = (Button)findViewById(R.id.Button01);
        b1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                 
                dialog = ProgressDialog.show(HTTPTest.this, "", "Downloading file...", true);
                 new Thread(new Runnable() {
                        public void run() {
                             downloadFile(dwnload_file_path, dest_file_path);
                        }
                      }).start();               
            }
        });
    }
     
    public void downloadFile(String url, String dest_file_path) {
          try {
              File dest_file = new File(dest_file_path);
              URL u = new URL(url);
              URLConnection conn = u.openConnection();
              int contentLength = conn.getContentLength();
              DataInputStream stream = new DataInputStream(u.openStream());
              byte[] buffer = new byte[contentLength];
              stream.readFully(buffer);
              stream.close();
              DataOutputStream fos = new DataOutputStream(new FileOutputStream(dest_file));
              fos.write(buffer);
              fos.flush();
              fos.close();
              hideProgressIndicator();
               
          } catch(FileNotFoundException e) {
              hideProgressIndicator();
              return; 
          } catch (IOException e) {
              hideProgressIndicator();
              return; 
          }
    }
     
    void hideProgressIndicator(){
        runOnUiThread(new Runnable() {
            public void run() {
                dialog.dismiss();
            }
        });  
    }
}

In your manifestation file add permission for

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

In your xml file add 

<?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="File Download Demo from Coderzheaven \n\nFile to download : http://coderzheaven.com/sample_folder/sample_file.png \n\nSaved Path : sdcard/\n"
    />
<Button
    android:text="Download File"
    android:id="@+id/Button01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
</Button>
</LinearLayout>


And you are good to go.........

Thursday, April 18, 2013

PHP: LOOP THROUGH EACH STRING LINE IN A TEXTAREA


To loop through all the string inputs entered on a new line for a textarea control is not particularly challenging and uses basic array functionality to achieve this.
To see the code in action:
//trim off excess whitespace off the whole
$text = trim($_POST['textareaname']);

//explode all separate lines into an array
$textAr = explode("\n", $text);

//trim all lines contained in the array.
$textAr = array_filter($textAr, 'trim');

//loop through the lines
foreach($textAr as $line){
echo "$line";
}

Uploading files to HTTP server using POST. Android SDK.

On Android Class just paste the code


HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;

String pathToOurFile = "/data/file_to_send.mp3";
String urlServer = "http://192.168.1.1/handle_upload.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary =  "*****";

int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;

try
{
FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );

URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();

// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);

// Enable POST method
connection.setRequestMethod("POST");

connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

outputStream = new DataOutputStream( connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);

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

// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);

while (bytesRead > 0)
{
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}

outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

// Responses from the server (code and message)
serverResponseCode = connection.getResponseCode();
serverResponseMessage = connection.getResponseMessage();

fileInputStream.close();
outputStream.flush();
outputStream.close();
}
catch (Exception ex)
{
//Exception handling
}

Now on php(Server side) page paste the code 


<?php
$target_path  = "./";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
 echo "The file ".  basename( $_FILES['uploadedfile']['name']).
 " has been uploaded";
} else{
 echo "There was an error uploading the file, please try again!";
}
?>



Friday, April 12, 2013

Generate Hash Key For Facebook 


In order to generate key hash you need to follow some easy steps.

1) Download Openssl from: http://code.google.com/p/openssl-for-windows/downloads/list

2) Make a openssl folder in C drive

3) Extract Zip files into openssl folder

4) Copy the File debug.keystore from .android folder in my case (C:\Users\SYSTEM.android) and paste into JDK bin Folder in my case (C:\Program Files\Java\jdk1.6.0_05\bin)

5) Open command prompt and give the path of JDK Bin folder in my case (C:\Program Files\Java\jdk1.6.0_05\bin).

6) Copy the code and hit enter keytool -exportcert -alias androiddebugkey -keystore debug.keystore > c:\openssl\bin\debug.txt

7) Now you need to enter password, Password = android.

8) See in openssl Bin folder you will get a file with the name of debug.txt

9) Now either you can restart command prompt or work with existing command prompt

10) comes to C drive and give the path of openssl Bin folder

11) copy the following code and paste openssl sha1 -binary debug.txt > debug_sha.txt

12) you will get debug_sha.txt in openssl bin folder

13) Again copy following code and paste openssl base64 -in debug_sha.txt > debug_base64.txt

14) you will get debug_base64.txt in openssl bin folder

15) open debug_base64.txt file Here is your Key hash.

Hope This Help....................