Wednesday, March 27, 2013

lazy list view

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


package com.fedorvlasov.lazylist;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class LazyAdapter extends BaseAdapter {

private Activity activity;
private String[] data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;

public LazyAdapter(Activity a, String[] _data)
{
activity = a;
data = _data;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}

public int getCount() {
return data.length;
}

public Object getItem(int position) {
return position;
}

public long getItemId(int position)
{
return position;
}

public View getView(int position, View convertView, ViewGroup parent)
{
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.item, null);

TextView text = (TextView) vi.findViewById(R.id.text);
;
ImageView image = (ImageView) vi.findViewById(R.id.image);
text.setText("item " + position);
imageLoader.displayImage(data[position], image);
return vi;
}
}

android gallery view

Monday, March 25, 2013

web view demo

MainActivity.java
-----------------------------------------------------------------

package net.kerul.alfatihah;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
//import android.webkit.WebSettings;
import android.widget.Toast;

public class MainActivity extends Activity {

// this version is using WebView to provide al-Fatihah in Arabic,
// and translation in Malay.

private MediaPlayer mp;
private TextView tvFooter, tvHeader;
private Boolean reload_sound;
// String url = "http://www.youtube.com/";
// String url = "http://news.yahoo.com/";
String url = "http://news.yahoo.com/chemical-romance-breaks-decade-plus-151936152.html";


ProgressDialog mProgress;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
// flag to reload sound
reload_sound = true;

// UIs activation
tvHeader = (TextView) findViewById(R.id.tvHeader);
// btnplay.setOnClickListener(this);
tvFooter = (TextView) findViewById(R.id.tvFooter);
// btnpause.setOnClickListener(this);

tvHeader.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
Log.e("-------Header--", " ");

// Toast.makeText(MainActivity.this, "Header",
// Toast.LENGTH_SHORT).show();
// Intent intent = new Intent(Intent.ACTION_VIEW,
// Uri.parse("http://www.progmaatic.com/"));

}
});

tvFooter.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
Log.e("-------Footer--", " ");

// Toast.makeText(MainActivity.this, "Footer",
// Toast.LENGTH_SHORT).show();
// Intent intent = new Intent(Intent.ACTION_VIEW,
// Uri.parse("http://www.progmaatic.com/"));

}
});

// btnstop = (Button) findViewById(R.id.btnstop);
// btnstop.setOnClickListener(this);
// btnstop.setEnabled(false);

// define webview
WebView webview = (WebView) findViewById(R.id.webview);
webview.setHorizontalScrollBarEnabled(false);
webview.loadUrl(url);

getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
Window.PROGRESS_VISIBILITY_ON);
// set Javascript
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
settings.setTextSize(WebSettings.TextSize.LARGER);
settings.setSupportZoom(false); // Zoom Control on web (You don't need
// this
// if ROM supports Multi-Touch
settings.setBuiltInZoomControls(true); // Enabl

// the init state of progress dialog
mProgress = ProgressDialog.show(this, "Loading",
"Please wait for a moment...");

// add a WebViewClient for WebView, which actually handles loading data
// from web
webview.setWebViewClient(new WebViewClient() {
// load url
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}

// when finish loading page
public void onPageFinished(WebView view, String url) {
if (mProgress.isShowing()) {
mProgress.dismiss();
}
}
});

// webview.loadUrl("http://www.google.com.bd/");

}

}

main.xml
---------------------------------------------------------


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

    <TableLayout
        android:id="@+id/tableLayout1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_gravity="center_vertical" >

            <TextView
                android:id="@+id/tvHeader"
                android:layout_width="fill_parent"
                android:layout_height="50dp"
                android:layout_weight="6.64"
                android:gravity="center"
                android:text="La Fleur"
                android:background="@android:color/black"
                android:textColor="@android:color/white"
                android:textSize="25dp"
                android:textStyle="bold"/>

        </TableRow>
    </TableLayout>

    <WebView
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.36" />

    <TextView
        android:id="@+id/tvFooter"
        android:layout_width="fill_parent"
        android:layout_height="25dp"
        android:layout_weight="0.03"
        android:gravity="center"
        android:text="Powered by Yahoo! News"
        android:background="@android:color/black"
        android:textColor="@android:color/white" />

</LinearLayout>


Manifest.xml
--------------------------------------------------------------

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

    <uses-sdk android:minSdkVersion="7" />

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

</manifest>

download: http://www.mediafire.com/?0gupsnyq09r7zkv


Tuesday, March 19, 2013

get file name from url


Strinh url = "http://coderzheaven.com/sample_folder/sample_file.png";
String fileName = url.substring( url.lastIndexOf('/')+1, url.length() );

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