Tuesday, March 19, 2013

download file from server

download: http://www.mediafire.com/?bufw8m1600bdu4y


package com.coderzheaven.pack;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class DownloadFileDemo1 extends Activity
{

    ProgressBar pb;
    Dialog dialog;
    int downloadedSize = 0;
    int totalSize = 0;
    TextView cur_val;
    String dwnload_file_path = "http://coderzheaven.com/sample_folder/sample_file.png";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        Button b = (Button) findViewById(R.id.b1);
        b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showProgress(dwnload_file_path);
     
       new Thread(new Runnable() {
           public void run() {
            downloadFile();
           }
         }).start();
}
});
    }
   
    void downloadFile(){
   
    try {
    URL url = new URL(dwnload_file_path);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestMethod("GET");
    urlConnection.setDoOutput(true);

    //connect
    urlConnection.connect();

    //set the path where we want to save the file    
    File SDCardRoot = Environment.getExternalStorageDirectory();
    //create a new file, to save the downloaded file
    File file = new File(SDCardRoot,"downloaded_file.png");

    FileOutputStream fileOutput = new FileOutputStream(file);

    //Stream used for reading the data from the internet
    InputStream inputStream = urlConnection.getInputStream();

    //this is the total size of the file which we are downloading
    totalSize = urlConnection.getContentLength();

    runOnUiThread(new Runnable() {
   public void run() {
    pb.setMax(totalSize);
   }  
});
   
    //create a buffer...
    byte[] buffer = new byte[1024];
    int bufferLength = 0;

    while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
    fileOutput.write(buffer, 0, bufferLength);
    downloadedSize += bufferLength;
    // update the progressbar //
    runOnUiThread(new Runnable() {
       public void run() {
        pb.setProgress(downloadedSize);
        float per = ((float)downloadedSize/totalSize) * 100;
        cur_val.setText("Downloaded " + downloadedSize + "KB / " + totalSize + "KB (" + (int)per + "%)" );
       }
    });
    }
    //close the output stream when complete //
    fileOutput.close();
    runOnUiThread(new Runnable() {
   public void run() {
    // pb.dismiss(); // if you want close it..
   }
});    
   
    } catch (final MalformedURLException e) {
    showError("Error : MalformedURLException " + e);  
    e.printStackTrace();
    } catch (final IOException e) {
    showError("Error : IOException " + e);  
    e.printStackTrace();
    }
    catch (final Exception e) {
    showError("Error : Please check your internet connection " + e);
    }    
    }
   
    void showError(final String err){
    runOnUiThread(new Runnable() {
   public void run() {
    Toast.makeText(DownloadFileDemo1.this, err, Toast.LENGTH_LONG).show();
   }
});
    }
   
    void showProgress(String file_path){
    dialog = new Dialog(DownloadFileDemo1.this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.myprogressdialog);
    dialog.setTitle("Download Progress");

    TextView text = (TextView) dialog.findViewById(R.id.tv1);
    text.setText("Downloading file from ... " + file_path);
    cur_val = (TextView) dialog.findViewById(R.id.cur_pg_tv);
    cur_val.setText("Starting download...");
    dialog.show();
   
    pb = (ProgressBar)dialog.findViewById(R.id.progress_bar);
    pb.setProgress(0);
    pb.setProgressDrawable(getResources().getDrawable(R.drawable.green_progress));
    }
}

android file upload

download: http://www.mediafire.com/?3om3bvkze75d4dd

MainActivity.java
----------------------------------
package com.example.fileupload;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity
{

private static final int SELECT_AUDIO = 2;
String selectedPath = "", serverResponseMessage;
int serverResponseCode;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.a);

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

String pathToOurFile = "/sdcard/159.jpg";
String urlServer = "http://192.168.1.107/fileUpload/index.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";

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

try {
Log.w("----in 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)
{
Log.w("----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)
{
Log.w("----catch (Exception ex) ---", " ");
ex.printStackTrace();
// Exception handling
}
}

}


ManiFest.xml
------------------

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.fileupload"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
 
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.fileupload.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>

serverscript in php
------------------------------
//run this command
//  cd /var/
//sudo chmod -R 777 www



<?php
$target_path = "uploads/";



$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!";

}

?>



Tuesday, March 12, 2013

android restful api connection


download: http://www.mediafire.com/?mtch4d3y0bhdcra

package com.androidtutorialbd.blogspot;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class City extends ListActivity
{
    private String result;
    private String deal_type;
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    List r = new ArrayList();
@Override
    public void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);

     
     
        new Thread(){
        public void run() {
        // Somewhere in your code this is called
        // in a thread which is not the user interface
        // thread

        try {
         URL url = new URL("https://monocle.livingsocial.com/v2/deals?category=travel&api-key=FEDEC03F3D1746F89C9C4ED95908FEDC");
         HttpURLConnection con = (HttpURLConnection) url
           .openConnection();
         String jsonString = readStream(con.getInputStream());
         if(jsonString!=null && jsonString.length()>0){
                 try
                 {
                  JSONObject rootObject = new JSONObject(jsonString);
                 
                     JSONArray jArray = rootObject.getJSONArray("deals");
                     JSONObject json_data = null;
                     for (int i = 0; i < jArray.length(); i++)
                     {
                         json_data = jArray.getJSONObject(i);
                         deal_type=json_data.getString("deal_type");
                       
                         //Log.d("-----"+json_data.getString("CITY_NAME")+"------", " " );
                         Log.i("-------"+" "+"deal_type="+deal_type+"-------", " ");
                     }
                 }
                 catch (JSONException e1)
                 {
                 
                 }
                 catch (ParseException e1)
                 {
                 
                 }
         }

         } catch (Exception e) {
         e.printStackTrace();
        }        
        };
        }.start();


    }
    private String readStream(InputStream in) {
    result = "";
 BufferedReader reader = null;
 StringBuilder sb = new StringBuilder();
 try {
   reader = new BufferedReader(new InputStreamReader(in));
   String line = "";
   while ((line = reader.readLine()) != null) {
     System.out.println(line);
     sb.append(line + "\n");
   }
   result = sb.toString();
 } catch (IOException e) {
   e.printStackTrace();
 } finally {
   if (reader != null) {
     try {
       reader.close();
     } catch (IOException e) {
       e.printStackTrace();
       }
   }
 }
 return result;
}
}

Monday, February 11, 2013

android clock making by thread


package com.example.helloandroid;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

protected int splashTime = 1000;
TextView tv1, tvTimeInMinute;
int timer = 0;

Integer timeCounter = 0;
public static Integer minuteCounter = 0;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(R.id.tvTimeCounter);
tvTimeInMinute = (TextView) findViewById(R.id.tvTimeInMinute);
Thread th = new Thread() {

@Override
public void run() {
try {

while (true) {
int secondStart = 0;

for (int i = secondStart; i < 5; i++) {
final Integer j = i;

Thread.sleep(1000);
runOnUiThread(new Runnable() {

public void run() {
try {
timeCounter++;

if (j == 4) {
Log.d("--if(timeCounter == 4)---minuteCounter="
+ minuteCounter.toString()
+ "------", " ");
minuteCounter++;
tvTimeInMinute
.setText(minuteCounter
.toString());
}
tv1.setText(j.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
});

}
}

} catch (InterruptedException e) {
}

}
};
th.start();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

return true;
}
}


activity_main.xml
------------------------------


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id = "@+id/tvTimeCounter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:padding="@dimen/padding_medium"
        android:text=""
        tools:context=".MainActivity" />

    <TextView
        android:id="@+id/tvTimeInMinute"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/tvTimeCounter"
        android:layout_alignBottom="@+id/tvTimeCounter"
        android:layout_marginRight="16dp"
        android:layout_toLeftOf="@+id/tvTimeCounter"
        android:text="00"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>




download: http://www.mediafire.com/?kinu8vnoabnh2c4

android customized grid view or extends grid view