November 07, 2013

Android Custom Listview.



main.xml

<?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" >

  <ListView
      android:id="@+id/Listview"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent" />
   
</LinearLayout>


Home.java

public class Home extends Activity{

private ListView HomeItemListView;
private  ListAdapter adapter;

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

      HomeItemListView = (ListView) findViewById(R.id.Listview);
      adapter = new ListAdapter(this);
       
        HomeItemListView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {

                ListItem listItem = (ListItem) adapter.getItem(position);
                System.out.println("Selected Item : " +  listItem.getItemID());
              
            }
        });

}

}

ListAdapter.java

import java.util.ArrayList;

import com.strat.stratpromo.R;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;


public class ListAdapter extends ArrayAdapter<ListItem> implements OnClickListener {
    public Context context;
    public ArrayList<HomeItem> HomeItemList;
    public ImageLoader imageLoader;
   
    public HomeListAdapter(Context context, int resource, ArrayList<HomeItem> HomeItemLst) {
        super(context, resource, HomeItemLst);
        this.context = context;
        this.HomeItemList = HomeItemLst;
        imageLoader = new ImageLoader(context);
    }
   
    @Override
    public int getCount() {
        if (HomeItemList != null)
            return HomeItemList.size();

        return 0;
    }

    @Override
    public HomeItem getItem(int position) {
        return HomeItemList.get(position);
    }
   
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View myConvertView = null;
        try {
            final HomeItem HomeItem = HomeItemList.get(position);
            myConvertView = convertView;
            if (myConvertView == null) {
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                myConvertView = inflater.inflate(R.layout.home_list_item_view, null);
            }
            ImageView CatImage = (ImageView) myConvertView.findViewById(R.id.list_image);
            TextView CatHeader = (TextView) myConvertView.findViewById(R.id.title);
            TextView CatDiscount = (TextView) myConvertView.findViewById(R.id.discount);
            TextView CatDescription = (TextView) myConvertView.findViewById(R.id.description);
           
            CatHeader.setText(HomeItem.getTitle());
            CatDiscount.setText(HomeItem.getDiscount());
            CatDescription.setText(HomeItem.getSubTitle());
           
            imageLoader.DisplayImage(HomeItem.getImageUrl(), CatImage);
       
            //    Bitmap bm = Helper.getBitmap(HomeItem.getImageUrl());
            /*String filePath = Helper.saveImageInExternalCacheDir(context, bm,
                        HomeItem.getTitle()+HomeItem.getPromotionID());*/
           
            //CatImage.setImageBitmap(bm);   
           
        } catch (Exception e) {
             e.printStackTrace();
        }
        return myConvertView;
    }
   
    @Override
    public long getItemId(int position) {
        return position;
    }

    public void onClick(View v) {
        // TODO Auto-generated method stub
       
    }
   
}

Importing Image From Gallery

In this tutorial I want to explain how to import images from Gallery to am imageview,

In this I am having One Button and One ImageView. While Tap on the button it will redirect to Gallery to Browse image. While we select an image it will display on the Imageview.

activity_main.xml

This is a Layout of main page. This layout contain One Button and one Imageview.



<LinearLayout 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"
    android:gravity="top|center"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/BtnSelectImg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Insert Image" />

    <ImageView
        android:id="@+id/ImgPhoto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/ic_launcher" />

</LinearLayout>

MainActivity.java


import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
   
    private static final int PICTURE_GALLERY_REQUEST = 22;

    Uri cameraUri;
   
    Button BtnSelectImage;
    private ImageView ImgPhoto;
    private String Camerapath ;
   
   
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        ImgPhoto = (ImageView) findViewById(R.id.ImgPhoto);
       
        BtnSelectImage = (Button) findViewById(R.id.BtnSelectImg);
        BtnSelectImage.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                // TODO Auto-generated method stub
                Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                  photoPickerIntent.setType("image/*");
                  startActivityForResult(photoPickerIntent, PICTURE_GALLERY_REQUEST);
            }
        });
       
    }
   
   
    @Override
    public void onActivityResult(final int requestCode, int resultCode, Intent data) {
        try {
            switch (requestCode) {
            case PICTURE_GALLERY_REQUEST:
                if (resultCode == RESULT_OK) {
                    try {
                        Uri selectedImage = data.getData();
                        ImgPhoto.setImageBitmap(decodeUri(selectedImage));
                    } catch (Exception e) {
                        Toast.makeText(this, "Couldn't load photo", Toast.LENGTH_LONG).show();
                    }
                }
                break;
              default:
                break;
            }
        } catch (Exception e) {
        }
    }
    
   

     private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException {
         BitmapFactory.Options o = new BitmapFactory.Options();
         o.inJustDecodeBounds = true;
         BitmapFactory.decodeStream(
                 getContentResolver().openInputStream(selectedImage), null, o);

         final int REQUIRED_SIZE = 100;

         int width_tmp = o.outWidth, height_tmp = o.outHeight;
         int scale = 1;
         while (true) {
             if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) {
                 break;
             }
             width_tmp /= 2;
             height_tmp /= 2;
             scale *= 2;
         }

         BitmapFactory.Options o2 = new BitmapFactory.Options();
         o2.inSampleSize = scale;
         //return BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o2);
         Bitmap b = BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o2);
         Matrix matrix = new Matrix();
         float rotation = rotationForImage(getApplicationContext(), selectedImage);
         if (rotation != 0f) {
               matrix.preRotate(rotation);
          }
         Bitmap resizedBitmap = Bitmap.createBitmap(
                 b, 0, 0, width_tmp, height_tmp, matrix, true);
         return resizedBitmap;
     }
    
    
     public static float rotationForImage(Context context, Uri uri) {
        if (uri.getScheme().equals("content")) {
        String[] projection = { Images.ImageColumns.ORIENTATION };
        Cursor c = context.getContentResolver().query(
                uri, projection, null, null, null);
        if (c.moveToFirst()) {
            return c.getInt(0);
        }
    } else if (uri.getScheme().equals("file")) {
        try {
            ExifInterface exif = new ExifInterface(uri.getPath());
            int rotation = (int)exifOrientationToDegrees(
                    exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                            ExifInterface.ORIENTATION_NORMAL));
            return rotation;
        } catch (IOException e) {
            Log.e("Photo Import", "Error checking exif", e);
        }
    }
        return 0f;
    }

    private static float exifOrientationToDegrees(int exifOrientation) {
    if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
        return 90;
    } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
        return 180;
    } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
        return 270;
    }
    return 0;
    }
   
}

November 02, 2013

How to pass Boolean, Int, String, Integer ArrayList, String ArrayList, int list and String List with an intent.

           
                 In this blog I want to explain How to pass Boolean, Int, String, Integer ArrayList, String ArrayList, int list and String List with an intent.


Intent
                Intent is an object that is used to launch an activity or to return information  from an activity.  To start a new activity using startActivity(intent).  To get information from another activity we start activity using startActivityForResult(intent, requestCode).


               Here in  FromPage.java we are adding  Boolean, Int, String, Integer ArrayList, String ArrayList, int list and String List values to an intent. In ToPage.java We extract added values will retrieve from intent. 


FromPage.java

ArrayList<Integer>  IntArrayList = new  ArrayList<Integer>(Arrays.asList(100,13,18,22,44,13));
ArrayList<String>  StringArrayList = new  ArrayList<String>(Arrays.asList("String1", "String2", "String3", "String4"));

        int[] intList = {4, 6, 3, 8, 2, 10};
        String[] StringList = {"String1", "String2", "String3", "String4"};

        Intent intent = new Intent(FrstPage.this, SecondPage.class);
        intent.putExtra("BoolValue", true);
        intent.putExtra("IntValue", 199);
        intent.putExtra("StringValue", "Test String");
        intent.putExtra("IntArrayList", IntArrayList);
        intent.putExtra("StringArrayList", StringArrayList);
        intent.putExtra("IntList", intList);
        intent.putExtra("StringList", StringList);
        startActivity(intent);



ToPage.java

            Intent intent = getIntent();
            boolean fullscreenAd =  intent.getBooleanExtra("BoolValue", false);
            int IntValue =  intent.getIntExtra("IntValue", 0);
            String StringValue =  intent.getStringExtra("StringValue");
            ArrayList<Integer> IntArrayList =  intent.getIntegerArrayListExtra("IntArrayList");
            ArrayList<String> StringArrayList =  intent.getStringArrayListExtra("StringArrayList");
            int[] intList =  intent.getIntArrayExtra("IntList");
            String[] StringList =  intent.getStringArrayExtra("StringList");