Thursday, 21 May 2015

Showing Base 64 image in WebView using Shared Preferences android

Create A Project
 This will store base 64 string into Shared Preferences and Will show in Webview
Paste Following code into it

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Base64;
import android.webkit.WebView;
import android.widget.ImageView;


public class MainActivity extends ActionBarActivity {

WebView webview;
ImageView img;
String url_to_show;
SharedPreferences sharedpreferences;

String byte_image_imageview = "";
public static final String MyPREFERENCES = "MyPrefs";
public static final String ByteImageString = "ByteImageString";


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedpreferences = getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);
webview = (WebView) findViewById(R.id.web_img);
String byte_image = "<div style='width='100%' height='100%''><img src='data:image/png;base64, Paste Any base 64 String Here' /></div>";

Editor editor = sharedpreferences.edit();
editor.putString(ByteImageString, byte_image);

editor.commit();
String imag_abc = sharedpreferences.getString(ByteImageString, "");
byte[] decodedString = Base64.decode(imag_abc, Base64.DEFAULT);
url_to_show = "<html><body>" + byte_image + "<html><body>";
// webview.setBackgroundColor(0x00000000);
webview.loadData(url_to_show, "text/html", "utf-8");

}

}
Paste Following Code into xml file

<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="${relativePackage}.${activityClass}" >

    <WebView
        android:id="@+id/web_img"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="42dp"
        android:layout_marginTop="64dp" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/web_img"
        android:layout_toRightOf="@+id/web_img"
        android:text="@string/txt_web" />


</RelativeLayout>

Run and Enjoy

Showing Base 64 image in using Shared Preference in Android

Step 1:
Create a project

And Copy Paste Below code into it.

<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="${relativePackage}.${activityClass}" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_alignLeft="@+id/web_img"
        android:layout_centerVertical="true"
        android:layout_toLeftOf="@+id/textView1"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/TextView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/imageView1"
        android:layout_toRightOf="@+id/imageView1"
        android:text="@string/txt_imageview" />

</RelativeLayout>

You can Do it For Both For image View and For WebView.
Copy paste Following code into main activity
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Base64;
import android.webkit.WebView;
import android.widget.ImageView;


public class MainActivity extends ActionBarActivity {

ImageView img;
String url_to_show;
SharedPreferences sharedpreferences;

String byte_image_imageview = "";
public static final String MyPREFERENCES = "MyPrefs";
public static final String ByteImageString = "ByteImageString";


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedpreferences = getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);

img = (ImageView) findViewById(R.id.imageView1);

byte_image_imageview = "Paste Any Base 64 String Here";
Editor editor = sharedpreferences.edit();
editor.putString(ByteImageString, byte_image_imageview);

editor.commit();
String imag_abc = sharedpreferences.getString(ByteImageString, "");
byte[] decodedString = Base64.decode(imag_abc, Base64.DEFAULT);
url_to_show = "<html><body>" + byte_image + "<html><body>";
// webview.setBackgroundColor(0x00000000);
webview.loadData(url_to_show, "text/html", "utf-8");

Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0,
decodedString.length);
img.setImageBitmap(decodedByte);

}



}


Showing Base 64 image in WebView android

Step1: Create a Project
Copy paste below code into xml file

<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="${relativePackage}.${activityClass}" >

    <WebView
        android:id="@+id/web_img"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="42dp"
        android:layout_marginTop="64dp" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/web_img"
        android:layout_toRightOf="@+id/web_img"
        android:text="@string/txt_web" />

</RelativeLayout>

Step2: Copy Paste Below code in java File
package com.example.imagewebview;

import android.content.Context;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Base64;
import android.webkit.WebView;

public class MainActivity extends ActionBarActivity {

WebView webview;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView) findViewById(R.id.web_img);

String byte_image = "<div style='width='100%' height='100%''><img src='data:image/png;base64,Copy paste any base 64 string here' /></div>";

url_to_show = "<html><body>" + byte_image + "<html><body>";
// webview.setBackgroundColor(0x00000000);
webview.loadData(url_to_show, "text/html", "utf-8");
}
}

Run and Enjoy

Showing Base 64 image in ImageView android

Showing base 64 Image in Android is very easy
Step 1:
Simply Create a Project 
And Paste Following code into It.
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Base64;
import android.widget.ImageView;

public class MainActivity extends ActionBarActivity {

ImageView img;
String byte_image_imageview = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

img = (ImageView) findViewById(R.id.imageView1);

byte_image_imageview = "COPY_PASTE_ANYBASE64_STRING_HERE";
byte[] decodedString = Base64.decode(byte_image_imageview, Base64.DEFAULT);


Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0,
decodedString.length);
img.setImageBitmap(decodedByte);
}

}
Step 2:
Copy Following Code in xml file
<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="${relativePackage}.${activityClass}" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_alignLeft="@+id/web_img"
        android:layout_centerVertical="true"
        android:layout_toLeftOf="@+id/textView1"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/TextView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/imageView1"
        android:layout_toRightOf="@+id/imageView1"
        android:text="@string/txt_imageview" />

</RelativeLayout>

Alphabetical Scroll in ListView

Step 1:
Create a Project named as Alphabetical Scroll
Step 2:
Copy Below code in to main activity
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;

import uk.co.brightec.alphabetscroller.AlphabetListAdapter.Item;
import uk.co.brightec.alphabetscroller.AlphabetListAdapter.Row;
import uk.co.brightec.alphabetscroller.AlphabetListAdapter.Section;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends ListActivity {

    private AlphabetListAdapter adapter = new AlphabetListAdapter();
    private GestureDetector mGestureDetector;
    private List < Object[] > alphabet = new ArrayList < Object[] > ();
    private HashMap < String, Integer > sections = new HashMap < String, Integer > ();
    private int sideIndexHeight;
    private static float sideIndexX;
    private static float sideIndexY;
    private int indexListSize;

    class SideIndexGestureListener extends GestureDetector.SimpleOnGestureListener {@
        Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            sideIndexX = sideIndexX - distanceX;
            sideIndexY = sideIndexY - distanceY;

            if (sideIndexX >= 0 && sideIndexY >= 0) {
                displayListItem();
            }

            return super.onScroll(e1, e2, distanceX, distanceY);
        }
    }

    @
    Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_alphabet);

        mGestureDetector = new GestureDetector(this, new SideIndexGestureListener());

        List < String > countries = populateCountries();
        Collections.sort(countries);

        List < Row > rows = new ArrayList < Row > ();
        int start = 0;
        int end = 0;
        String previousLetter = null;
        Object[] tmpIndexItem = null;
        Pattern numberPattern = Pattern.compile("[0-9]");

        for (String country: countries) {
            String firstLetter = country.substring(0, 1);

            // Group numbers together in the scroller
            if (numberPattern.matcher(firstLetter).matches()) {
                firstLetter = "#";
            }

            // If we've changed to a new letter, add the previous letter to the alphabet scroller
            if (previousLetter != null && !firstLetter.equals(previousLetter)) {
                end = rows.size() - 1;
                tmpIndexItem = new Object[3];
                tmpIndexItem[0] = previousLetter.toUpperCase(Locale.UK);
                tmpIndexItem[1] = start;
                tmpIndexItem[2] = end;
                alphabet.add(tmpIndexItem);

                start = end + 1;
            }

            // Check if we need to add a header row
            if (!firstLetter.equals(previousLetter)) {
                rows.add(new Section(firstLetter));
                sections.put(firstLetter, start);
            }

            // Add the country to the list
            rows.add(new Item(country));
            previousLetter = firstLetter;
        }

        if (previousLetter != null) {
            // Save the last letter
            tmpIndexItem = new Object[3];
            tmpIndexItem[0] = previousLetter.toUpperCase(Locale.UK);
            tmpIndexItem[1] = start;
            tmpIndexItem[2] = rows.size() - 1;
            alphabet.add(tmpIndexItem);
        }

        adapter.setRows(rows);
        setListAdapter(adapter);

        updateList();
    }

    @
    Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mGestureDetector.onTouchEvent(event)) {
            return true;
        } else {
            return false;
        }
    }

    public void updateList() {
        LinearLayout sideIndex = (LinearLayout) findViewById(R.id.sideIndex);
        sideIndex.removeAllViews();
        indexListSize = alphabet.size();
        if (indexListSize < 1) {
            return;
        }

        int indexMaxSize = (int) Math.floor(sideIndex.getHeight() / 20);
        int tmpIndexListSize = indexListSize;
        while (tmpIndexListSize > indexMaxSize) {
            tmpIndexListSize = tmpIndexListSize / 2;
        }
        double delta;
        if (tmpIndexListSize > 0) {
            delta = indexListSize / tmpIndexListSize;
        } else {
            delta = 1;
        }

        TextView tmpTV;
        for (double i = 1; i <= indexListSize; i = i + delta) {
            Object[] tmpIndexItem = alphabet.get((int) i - 1);
            String tmpLetter = tmpIndexItem[0].toString();

            tmpTV = new TextView(this);
            tmpTV.setText(tmpLetter);
            tmpTV.setGravity(Gravity.CENTER);
            tmpTV.setTextSize(15);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1);
            tmpTV.setLayoutParams(params);
            sideIndex.addView(tmpTV);
        }

        sideIndexHeight = sideIndex.getHeight();

        sideIndex.setOnTouchListener(new OnTouchListener() {@
            Override
            public boolean onTouch(View v, MotionEvent event) {
                // now you know coordinates of touch
                sideIndexX = event.getX();
                sideIndexY = event.getY();

                // and can display a proper item it country list
                displayListItem();

                return false;
            }
        });
    }

    public void displayListItem() {
        LinearLayout sideIndex = (LinearLayout) findViewById(R.id.sideIndex);
        sideIndexHeight = sideIndex.getHeight();
        // compute number of pixels for every side index item
        double pixelPerIndexItem = (double) sideIndexHeight / indexListSize;

        // compute the item index for given event position belongs to
        int itemPosition = (int)(sideIndexY / pixelPerIndexItem);

        // get the item (we can do it since we know item index)
        if (itemPosition < alphabet.size()) {
            Object[] indexItem = alphabet.get(itemPosition);
            int subitemPosition = sections.get(indexItem[0]);

            //ListView listView = (ListView) findViewById(android.R.id.list);
            getListView().setSelection(subitemPosition);
        }
    }

    private List < String > populateCountries() {
        List < String > countries = new ArrayList < String > ();
        countries.add("Afghanistan");
        countries.add("Albania");
        countries.add("Bahrain");
        countries.add("Bangladesh");
        countries.add("Cambodia");
        countries.add("Cameroon");
        countries.add("Denmark");
        countries.add("Djibouti");
        countries.add("East Timor");
        countries.add("Ecuador");
        countries.add("Fiji");
        countries.add("Finland");
        countries.add("Gabon");
        countries.add("Georgia");
        countries.add("Haiti");
        countries.add("Holy See");
        countries.add("Iceland");
        countries.add("India");
        countries.add("Jamaica");
        countries.add("Japan");
        countries.add("Kazakhstan");
        countries.add("Kenya");
        countries.add("Laos");
        countries.add("Latvia");
        countries.add("Macau");
        countries.add("Macedonia");
        countries.add("Namibia");
        countries.add("Nauru");
        countries.add("Oman");
        countries.add("Pakistan");
        countries.add("Palau");
        countries.add("Qatar");
        countries.add("Romania");
        countries.add("Russia");
        countries.add("Saint Kitts and Nevis");
        countries.add("Saint Lucia");
        countries.add("Taiwan");
        countries.add("Tajikistan");
        countries.add("Uganda");
        countries.add("Ukraine");
        countries.add("Vanuatu");
        countries.add("Venezuela");
        countries.add("Yemen");
        countries.add("Zambia");
        countries.add("Zimbabwe");
        countries.add("0");
        countries.add("2");
        countries.add("9");
        return countries;
    }
}

Step 2: Create a class named as AlphabetListAdapter paste below code into it

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

public class AlphabetListAdapter extends BaseAdapter {

public static abstract class Row {}

public static final class Section extends Row {
public final String text;

public Section(String text) {
this.text = text;
}
}

public static final class Item extends Row {
public final String text;

public Item(String text) {
this.text = text;
}
}

private List < Row > rows;

public void setRows(List < Row > rows) {
this.rows = rows;
}

@Override
public int getCount() {
return rows.size();
}

@Override
public Row getItem(int position) {
return rows.get(position);
}

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

@Override
public int getViewTypeCount() {
return 2;
}

@Override
public int getItemViewType(int position) {
if (getItem(position) instanceof Section) {
return 1;
} else {
return 0;
}
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;

if (getItemViewType(position) == 0) { // Item
if (view == null) {
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = (LinearLayout) inflater.inflate(R.layout.row_item, parent, false);
}

Item item = (Item) getItem(position);
TextView textView = (TextView) view.findViewById(R.id.textView1);
textView.setText(item.text);
} else { // Section
if (view == null) {
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = (LinearLayout) inflater.inflate(R.layout.row_section, parent, false);
}

Section section = (Section) getItem(position);
TextView textView = (TextView) view.findViewById(R.id.textView1);
textView.setText(section.text);
}

return view;
}

}
Step 3: paste following code into activity_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" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:fastScrollEnabled="true" />

    <LinearLayout
        android:id="@+id/sideIndex"
        android:layout_width="40dip"
        android:layout_height="fill_parent"
        android:background="#FFF"
        android:gravity="center_horizontal"
        android:orientation="vertical" >
    </LinearLayout>

</LinearLayout>
Step 4: Create an xml file named as row item paste following code into it
<?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="horizontal"
    android:padding="10dp" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

</LinearLayout>

Step 5: Create an xml file named as row section  paste following code into it
<?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:background="@android:color/darker_gray"
    android:orientation="horizontal"
    android:paddingBottom="2dp"
    android:paddingLeft="10dp"
    android:paddingTop="2dp" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textColor="@android:color/white"
        android:textStyle="bold" />

</LinearLayout>
Done:)


Quick Scroll in Android ListView













Step 1: Create a project named as Quick Scroll:

Step 2: Copy Below Code into Main Activity

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Set;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SectionIndexer;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
ListView lv;

/* Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

lv = (ListView) findViewById(R.id.listView1);

LinkedList<String> mLinked = new LinkedList<String>();
for (int i = 0; i < COUNTRIES.length; i++) {
mLinked.add(COUNTRIES[i]);
}

// setListAdapter(new MyListAdaptor(this, mLinked));

// ListView lv = getListView();
lv.setAdapter(new MyListAdaptor(this, mLinked));
lv.setFastScrollEnabled(true);

lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}

static final String[] COUNTRIES = new String[] { "Afghanistan", "Albania",
"Algeria", "American Samoa", "Andorra", "Angola", "Anguilla",
"Antarctica", "Antigua and Barbuda", "Argentina", "Armenia",
"Aruba", "Australia", "Austria", "Azerbaijan", "Bahrain",
"Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin",
"Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegovina",
"Botswana", "Bouvet Island", "Brazil",
"British Indian Ocean Territory", "British Virgin Islands",
"Brunei", "Bulgaria", "Burkina Faso", "Burundi", "Cote d'Ivoire",
"Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands",
"Central African Republic", "Chad", "Chile", "China",
"Christmas Island", "Cocos (Keeling) Islands", "Colombia",
"Comoros", "Congo", "Cook Islands", "Costa Rica", "Croatia",
"Cuba", "Cyprus", "Czech Republic",
"Democratic Republic of the Congo", "Denmark", "Djibouti",
"Dominica", "Dominican Republic", "East Timor", "Ecuador", "Egypt",
"El Salvador", "Equatorial Guinea", "Eritrea", "Estonia",
"Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji",
"Finland", "Former Yugoslav Republic of Macedonia", "France",
"French Guiana", "French Polynesia", "French Southern Territories",
"Gabon", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece",
"Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala",
"Guinea", "Guinea-Bissau", "Guyana", "Haiti",
"Heard Island and McDonald Islands", "Honduras", "Hong Kong",
"Hungary", "Iceland", "India", "Indonesia", "Iran", "Iraq",
"Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan",
"Kazakhstan", "Kenya", "Kiribati", "Kuwait", "Kyrgyzstan", "Laos",
"Latvia", "Lebanon", "Lesotho", "Liberia", "Libya",
"Liechtenstein", "Lithuania", "Luxembourg", "Macau", "Madagascar",
"Malawi", "Malaysia", "Maldives", "Mali", "Malta",
"Marshall Islands", "Martinique", "Mauritania", "Mauritius",
"Mayotte", "Mexico", "Micronesia", "Moldova", "Monaco", "Mongolia",
"Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia",
"Nauru", "Nepal", "Netherlands", "Netherlands Antilles",
"New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria",
"Niue", "Norfolk Island", "North Korea", "Northern Marianas",
"Norway", "Oman", "Pakistan", "Palau", "Panama",
"Papua New Guinea", "Paraguay", "Peru", "Philippines",
"Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar",
"Reunion", "Romania", "Russia", "Rwanda", "Sqo Tome and Principe",
"Saint Helena", "Saint Kitts and Nevis", "Saint Lucia",
"Saint Pierre and Miquelon", "Saint Vincent and the Grenadines",
"Samoa", "San Marino", "Saudi Arabia", "Senegal", "Seychelles",
"Sierra Leone", "Singapore", "Slovakia", "Slovenia",
"Solomon Islands", "Somalia", "South Africa",
"South Georgia and the South Sandwich Islands", "South Korea",
"Spain", "Sri Lanka", "Sudan", "Suriname",
"Svalbard and Jan Mayen", "Swaziland", "Sweden", "Switzerland",
"Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand",
"The Bahamas", "The Gambia", "Togo", "Tokelau", "Tonga",
"Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan",
"Turks and Caicos Islands", "Tuvalu", "Virgin Islands", "Uganda",
"Ukraine", "United Arab Emirates", "United Kingdom",
"United States", "United States Minor Outlying Islands", "Uruguay",
"Uzbekistan", "Vanuatu", "Vatican City", "Venezuela", "Vietnam",
"Wallis and Futuna", "Western Sahara", "Yemen", "Yugoslavia",
"Zambia", "Zimbabwe" };

/**
* The List row creator
*/
class MyListAdaptor extends ArrayAdapter<String> implements SectionIndexer {

HashMap<String, Integer> alphaIndexer;
String[] sections;

public MyListAdaptor(Context context, LinkedList<String> items) {
super(context, R.layout.list_item, items);

alphaIndexer = new HashMap<String, Integer>();
int size = items.size();

for (int x = 0; x < size; x++) {
String s = items.get(x);
// get the first letter of the store
String ch = s.substring(0, 1);
// convert to uppercase otherwise lowercase a -z will be sorted
// after upper A-Z
ch = ch.toUpperCase();
// put only if the key does not exist
if (!alphaIndexer.containsKey(ch))
alphaIndexer.put(ch, x);
}

Set<String> sectionLetters = alphaIndexer.keySet();
// create a list from the set to sort
ArrayList<String> sectionList = new ArrayList<String>(
sectionLetters);
Collections.sort(sectionList);
sections = new String[sectionList.size()];
sections = sectionList.toArray(sections);
}

@Override
public int getPositionForSection(int section) {
return alphaIndexer.get(sections[section]);
}

@Override
public int getSectionForPosition(int position) {
return 0;
}

@Override
public Object[] getSections() {
return sections;
}
}
}

Step 3: Copy Below Code into xml file activity_main


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

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

</LinearLayout>

Step 4: Create an XML layout File named as list_item and paste the Following Code into It
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="16sp" >
</TextView>


Run and Enjoy :)
Out Put Will Be like This :)

Wednesday, 29 April 2015

Working With Android SQLITE

Step 1 : Make and Android project named “MycontentProvider”.
Step 2: Paste the following code in MainActivity.java file.

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
 public class MainActivity extends Activity
 {
        @Override protected void onCreate(Bundle savedInstanceState)
        {
               super.onCreate(savedInstanceState);
               setContentView(R.layout.activity_main);
        }
        @Override public boolean onCreateOptionsMenu(Menu menu)
        {
               getMenuInflater().inflate(R.menu.main, menu);
               return true;
        }
        public void onClickAddName(View view)
        {
               // Add a new student record
               ContentValues values = new ContentValues();
               values.put(StudentsProvider.NAME, ((EditText)findViewById(R.id.txtName)).getText().toString());
               values.put(StudentsProvider.GRADE, ((EditText)findViewById(R.id.txtGrade)).getText().toString());
               Uri uri = getContentResolver().insert( StudentsProvider.CONTENT_URI, values);
               Toast.makeText(getBaseContext(), uri.toString(), Toast.LENGTH_LONG).show();
        }
        public void onClickRetrieveStudents(View view)
        {
               // Retrieve student records
               String URL = "content://com.example.provider.College/students";
               Uri students = Uri.parse(URL);
               Cursor c = managedQuery(students, null, null, null, "name");
               if (c.moveToFirst())
               {
                      do
                      {
                            Toast.makeText(this, c.getString(c.getColumnIndex(StudentsProvider._ID)) + ", " + c.getString(c.getColumnIndex( StudentsProvider.NAME)) + ", " + c.getString(c.getColumnIndex( StudentsProvider.GRADE)), Toast.LENGTH_SHORT).show();
                      }
                      while (c.moveToNext());
               }
        }
        
        }
Step 3 : Make another java class named “StudentsProvider”.
Step 4 : Paste the following code in StudentsProvider.java file.

import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
 public class StudentsProvider extends ContentProvider
 {
        static final String PROVIDER_NAME = "com.example.provider.College";
        static final String URL = "content://" + PROVIDER_NAME + "/students";
        static final Uri CONTENT_URI = Uri.parse(URL);
        static final String _ID = "_id";
        static final String NAME = "name";
        static final String GRADE = "grade";
        private static HashMap<String, String> STUDENTS_PROJECTION_MAP;
        static final int STUDENTS = 1;
        static final int STUDENT_ID = 2;
        static final UriMatcher uriMatcher;
        private SQLiteDatabase db;
        static final String DATABASE_NAME = "College";
        static final String STUDENTS_TABLE_NAME = "students";
        static final int DATABASE_VERSION = 1;
        static final String CREATE_DB_TABLE = " CREATE TABLE " + STUDENTS_TABLE_NAME + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, " + " name TEXT NOT NULL, " + " grade TEXT NOT NULL);";
        
        static
        {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI(PROVIDER_NAME, "students", STUDENTS);
        uriMatcher.addURI(PROVIDER_NAME, "students/#", STUDENT_ID);
        }
        /** * Database specific constant declarations */
        /** * Helper class that actually creates and manages * the provider's underlying data repository. */
        private static class DatabaseHelper extends SQLiteOpenHelper
        {
               DatabaseHelper(Context context)
               {
                      super(context, DATABASE_NAME, null, DATABASE_VERSION);
               }
               @Override
               public void onCreate(SQLiteDatabase db)
               {
                      db.execSQL(CREATE_DB_TABLE);
               }
               @Override
               public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
               {
                      db.execSQL("DROP TABLE IF EXISTS " + STUDENTS_TABLE_NAME);
                      onCreate(db);
               }
               
         }
        @Override
        public boolean onCreate()
        {
               Context context = getContext();
               DatabaseHelper dbHelper = new DatabaseHelper(context);
               /** * Create a write able database which will trigger its * creation if it doesn't already exist. */
               db = dbHelper.getWritableDatabase();
               return (db == null)? false:true;
        }
        @Override
        public Uri insert(Uri uri, ContentValues values)
        {
               /** * Add a new student record */
               long rowID = db.insert( STUDENTS_TABLE_NAME, "", values);
               /** * If record is added successfully */
               if (rowID > 0)
               {
                      Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
                      getContext().getContentResolver().notifyChange(_uri, null); return _uri;
             
               }
               throw new SQLException("Failed to add a record into " + uri);
        }
        @Override
        public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
        {
               SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
               qb.setTables(STUDENTS_TABLE_NAME);
               switch (uriMatcher.match(uri))
               {
               case STUDENTS: qb.setProjectionMap(STUDENTS_PROJECTION_MAP);
               break;
               case STUDENT_ID: qb.appendWhere( _ID + "=" + uri.getPathSegments().get(1));
               break;
               default:
                      throw new IllegalArgumentException("Unknown URI " + uri);
               }
               if (sortOrder == null || sortOrder == "")
               {
                      /** * By default sort on student names */
                      sortOrder = NAME;
               }
               Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
               /** * register to watch a content URI for changes */
               c.setNotificationUri(getContext().getContentResolver(), uri);
               return c;
               }
        @Override
        public int delete(Uri uri, String selection, String[] selectionArgs)
        {
               int count = 0; switch (uriMatcher.match(uri))
               {
               case STUDENTS: count = db.delete(STUDENTS_TABLE_NAME, selection, selectionArgs);
               break;
               case STUDENT_ID: String id = uri.getPathSegments().get(1);
               count = db.delete( STUDENTS_TABLE_NAME, _ID + " = " + id + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);
               break;
               default:
                      throw new IllegalArgumentException("Unknown URI " + uri);
               }
               getContext().getContentResolver().notifyChange(uri, null);
               return count;
        }
        @Override
        public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)
        {
               int count = 0; switch (uriMatcher.match(uri))
               {
               case STUDENTS: count = db.update(STUDENTS_TABLE_NAME, values, selection, selectionArgs);
               break;
               case STUDENT_ID: count = db.update(STUDENTS_TABLE_NAME, values, _ID + " = " + uri.getPathSegments().get(1) + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);
               break;
               default:
                      throw new IllegalArgumentException("Unknown URI " + uri );
               }
               getContext().getContentResolver().notifyChange(uri, null);return count;
}
        @Override
        public String getType(Uri uri)
        {
               switch (uriMatcher.match(uri))
               {
               /** * Get all student records */
               case STUDENTS: return "vnd.android.cursor.dir/vnd.example.students";
               /** * Get a particular student */
               case STUDENT_ID: return "vnd.android.cursor.item/vnd.example.students";
               default: throw new IllegalArgumentException("Unsupported URI: " + uri);
               }
        }
        }
Step 5 : Paste the following code in activity_main.xml file.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Name" />

    <EditText
        android:id="@+id/txtName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Grade" />

    <EditText
        android:id="@+id/txtGrade"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btnAdd"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="onClickAddName"
        android:text="Add Name" />

    <Button
        android:id="@+id/btnRetrieve"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="onClickRetrieveStudents"
        android:text="Retrieve Students" />

</LinearLayout>

Step 6 : Pate the following code in strings.xml file.
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">mycontentprovider</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>

</resources>



Step 7 : Paste the following code in AndroidManifest.xml file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mycontentprovider"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

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

        <provider
            android:name="StudentsProvider"
            android:authorities="com.example.provider.College" >
        </provider>
    </application>

</manifest>

Step 8 : Run your program.