Saturday 14 December 2013

Custom Toast

1) in Activity.java
==============
final View toastView = getLayoutInflater().inflate(
R.layout.custom_toast,(ViewGroup) findViewById(R.id.toastLayout));
ImageView imageView = (ImageView) toastView
.findViewById(R.id.image);
imageView.setImageResource(R.drawable.ic_info);

// imageView.setBackgroundDrawable(bitmapDrawable);
TextView textView = (TextView) toastView.findViewById(R.id.text);
textView.setText("Take a Clear photo of the Ticket");
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
toast = new Toast(HomeActivity.this);
toast.setGravity(Gravity.TOP, 0, 100);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(toastView);
toast.show();
}
}, 2000);

2) custom_toast.xml
==============
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toastLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@layout/roundborder"
    android:orientation="horizontal"
    android:padding="10dp" >

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_marginRight="1dp" />

    <TextView
        android:id="@+id/text"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:layout_marginRight="4dp"
        android:gravity="center"
        android:paddingLeft="5dip"
        android:text="Take a clear photo of the Ticket"
        android:textColor="#FFF"
        android:textSize="16dip" />

</LinearLayout>

Friday 13 December 2013

RSS Feed Reader

1)MainActivity.java
==============
package com.example.rssfeed;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import nl.matshofman.saxrssreader.RssFeed;
import nl.matshofman.saxrssreader.RssItem;
import nl.matshofman.saxrssreader.RssReader;
import org.xml.sax.SAXException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends Activity {
private TextView txtTitle;

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

txtTitle = (TextView)findViewById(R.id.txtTitle);

if (android.os.Build.VERSION.SDK_INT > 9) {
   StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
   StrictMode.setThreadPolicy(policy);
}

URL url = null;
try {
url = new URL("http://www.vogella.com/article.rss");
} catch (MalformedURLException e) {
e.printStackTrace();
}
RssFeed feed = null;
try {
feed = RssReader.read(url);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

ArrayList<RssItem> rssItems = feed.getRssItems();
for(RssItem rssItem : rssItems) {
   Log.i("RSS Reader", rssItem.getTitle());
   txtTitle.setText(rssItem.getTitle());
}
}
}
2)Download library from

3)Manifest Permissions
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

ShowMultipleFileDownloadProgression

1) Create class CustomListViewAdapter.java
==============================
package com.example.showdownloadprogression;

import java.util.List;
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;

public class CustomListViewAdapter extends BaseAdapter {

   Context context;
   List<RowItem> rowItems;

   public CustomListViewAdapter(Context context, List<RowItem> items) {
       this.context = context;
       this.rowItems = items;
   }

   private class ViewHolder {
       ImageView imageView;
   }

   public int getCount() {
       return rowItems.size();
   }

   public Object getItem(int position) {
       return rowItems.get(position);
   }

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

   public View getView(int position, View convertView, ViewGroup parent) {
       ViewHolder holder = null;
       LayoutInflater mInflater = (LayoutInflater) context
               .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
       if (convertView == null) {
           convertView = mInflater.inflate(R.layout.list_item, null);
           holder = new ViewHolder();
           holder.imageView = (ImageView) convertView
                   .findViewById(R.id.thumbnail);
           convertView.setTag(holder);
       } else {
           holder = (ViewHolder) convertView.getTag();
       }
       RowItem rowItem = (RowItem) getItem(position);
       holder.imageView.setImageBitmap(rowItem.getBitmapImage());
       return convertView;
   }
}

2) Create class FileUtils.java
====================
package com.example.showdownloadprogression;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileUtils {

    public static void close(InputStream stream) {
        if(stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(OutputStream stream) {
        if(stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


3) Create class MainActivity.java
=======================
package com.example.showdownloadprogression;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;
public class MainActivity extends Activity {
    ProgressDialog progressDialog;
    CustomListViewAdapter listViewAdapter;
    ListView listView;
    public static final String URL =
        "http://theopentutorials.com/totwp331/wp-content/uploads/totlogo.png";
    public static final String URL1 =
        "http://theopentutorials.com/totwp331/wp-content/uploads/totlogo.png";
    public static final String URL2 =
        "http://theopentutorials.com/totwp331/wp-content/uploads/totlogo.png";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            listView = (ListView) findViewById(R.id.imageList);
        /*Creating and executing background task*/
        GetXMLTask task = new GetXMLTask(this);
        task.execute(new String[] { URL, URL1, URL2 });
        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("In progress...");
        progressDialog.setMessage("Loading...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setIndeterminate(false);
        progressDialog.setMax(100);
        progressDialog.setIcon(R.drawable.arrow);
        progressDialog.setCancelable(true);
        progressDialog.show();
    }
// 
//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.activity_main, menu);
//        return true;
//    }
    private class GetXMLTask extends AsyncTask<String, Integer, List<RowItem>> {
        private Activity context;
        List<RowItem> rowItems;
        int noOfURLs;
        public GetXMLTask(Activity context) {
            this.context = context;
        }
        @Override
        protected List<RowItem> doInBackground(String... urls) {
            noOfURLs = urls.length;
            rowItems = new ArrayList<RowItem>();
            Bitmap map = null;
            for (String url : urls) {
                map = downloadImage(url);
                rowItems.add(new RowItem(map));
            }
            return rowItems;
        }
        private Bitmap downloadImage(String urlString) {
            int count = 0;
            Bitmap bitmap = null;
            URL url;
            InputStream inputStream = null;
            BufferedOutputStream outputStream = null;
            try {
                url = new URL(urlString);
                URLConnection connection = url.openConnection();
                int lenghtOfFile = connection.getContentLength();
                inputStream = new BufferedInputStream(url.openStream());
                ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
                outputStream = new BufferedOutputStream(dataStream);
                byte data[] = new byte[512];
                long total = 0;
                while ((count = inputStream.read(data)) != -1) {
                    total += count;
                    /*publishing progress update on UI thread.
                    Invokes onProgressUpdate()*/
                    publishProgress((int)((total*100)/lenghtOfFile));
                    // writing data to byte array stream
                    outputStream.write(data, 0, count);
                }
                outputStream.flush();
                BitmapFactory.Options bmOptions = new BitmapFactory.Options();
                bmOptions.inSampleSize = 1;
                byte[] bytes = dataStream.toByteArray();
                bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length,bmOptions);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                FileUtils.close(inputStream);
                FileUtils.close(outputStream);
            }
            return bitmap;
        }
        protected void onProgressUpdate(Integer... progress) {
            progressDialog.setProgress(progress[0]);
            if(rowItems != null) {
                progressDialog.setMessage("Loading " + (rowItems.size()+1) + "/" + noOfURLs);
            }
       }
       @Override
       protected void onPostExecute(List<RowItem> rowItems) {
        listViewAdapter = new CustomListViewAdapter(context, rowItems);
        listView.setAdapter(listViewAdapter);
        progressDialog.dismiss();
       }    
    }
}

4) Create class RowItem.java
====================
package com.example.showdownloadprogression;

import android.graphics.Bitmap;

public class RowItem {
 
    private Bitmap bitmapImage;
    public RowItem(Bitmap bitmapImage) {
        this.bitmapImage =  bitmapImage;
    }
    public Bitmap getBitmapImage() {
        return bitmapImage;
    }
    public void setBitmapImage(Bitmap bitmapImage) {
        this.bitmapImage = bitmapImage;
    }
}

5)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"
    tools:context=".MainActivity" >
    <ListView
        android:id="@+id/imageList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</RelativeLayout>

6) list_item.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="wrap_content"
    android:orientation="vertical"
    android:padding="10dp" >
    <ImageView
        android:id="@+id/thumbnail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

7) in values-v11 style.xml
=================
<resources>

    <style name="AppBaseTheme" parent="android:Theme.Holo.Light">
        <!-- API 11 theme customizations can go here. -->
    </style>
</resources>

8) in values-v14 style.xml
==================
<resources>

  <style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">
        <!-- API 14 theme customizations can go here. -->
    </style>
</resources>

9) Don't forget to give permission of "Internet" & "Access_Network_State"