Monthly Archives: October 2012

How to pass an arraylist value from one activity to another in android?

This simple example shows how to pass an ArrayList from one activity to another in Android.
This is the first activity on which we are sending the arrayList.

package com.coderzheaven.passarraylist;

import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        final ArrayList<String> arr = new ArrayList<String>();
        arr.add("Hello");
        arr.add("CoderzHeaven");
        
        findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, Second.class);
				intent.putExtra("array_list", arr);
				startActivity(intent);
				
			}
		});
        
        
    }
}

Now this is the second activity in which we are receiving the passed arrayList.

package com.coderzheaven.passarraylist;

import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;

public class Second extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_activity);
        
        Bundle b = getIntent().getExtras();
        
        if(b!=null){
        	ArrayList<String> arr = (ArrayList<String>)b.getStringArrayList("array_list");
        	System.out.println(arr);
        }    
     
    }
}

This is the AndroidManifest file.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.coderzheaven.passarraylist"
    android:versionCode="1"
    android:versionName="1.0" >

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

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

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

</manifest>

Please check the LogCat for the Output.

Download complete tutorial PDF from below.

Pass ArrayList Tutorial PDF

ActionBar with Search Option and other options in Android.

I have already shown some examples with ActionBar.
This is the example showing how to start with ActionBar in android.

1. Android removes the need of Menu button from devices with ActionBar.

2. How to start with ActionBar in Android?

3. Dynamically Adding, Removing, Toggling and Removing all ActionBar Tabs in Android – Part 2?

Now today I will show you another example in which we will put a searchbar along with other buttons in the ActionBar and Listen to the search and Listen to the button select.

This is how we do this.

Take a look at the screenshot.

ActionBar

ActionBar

ActionBar

ActionBar

First in your project “res” folder create a folder named “menu”. the create an xml inside this folder named “actions.xml”.
Now copy these to this xml.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/action_search"
          android:icon="@android:drawable/ic_menu_search"
          android:title="Action Bar Search"
          android:showAsAction="ifRoom"
          android:actionViewClass="android.widget.SearchView" />
    <item android:id="@+id/action_add"
          android:icon="@android:drawable/ic_menu_add"
          android:title="Action Bar Add" />
    <item android:id="@+id/action_edit"
          android:icon="@android:drawable/ic_menu_edit"
          android:showAsAction="always"
          android:title="Action Bar Edit" />
    <item android:id="@+id/action_share"
          android:icon="@android:drawable/ic_menu_share"
          android:title="Action Bar Share"
          android:showAsAction="ifRoom" />
</menu>

OK now we go to the java code. In your Activity file copy this code.

package com.coderzheaven.actionbarsearch;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.TextView;
import android.widget.Toast;

public class ActionBarWithSearch extends Activity  implements OnQueryTextListener {
    TextView mSearchText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSearchText = new TextView(this);
        mSearchText.setPadding(10, 10, 10, 10);
        mSearchText.setText("Action Bar Usage example from CoderzHeaven");
        setContentView(mSearchText);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.actions, menu);
        SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
        searchView.setOnQueryTextListener(this);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean    onOptionsItemSelected       (MenuItem item) {
        Toast.makeText(this, "Selected Item: " + item.getTitle(), Toast.LENGTH_SHORT).show();
        return true;
    }

    // The following callbacks are called for the SearchView.OnQueryChangeListener
    public boolean onQueryTextChange(String newText) {
        newText = newText.isEmpty() ? "" : "Query so far: " + newText;
        mSearchText.setText(newText);
        mSearchText.setTextColor(Color.GREEN);
        return true;
    }

    public boolean      onQueryTextSubmit      (String query) {
        //Toast.makeText(this, "Searching for: " + query + "...", Toast.LENGTH_SHORT).show();
        mSearchText.setText("Searching for: " + query + "...");
        mSearchText.setTextColor(Color.RED);
        return true;
    }
}

Here “onQueryTextChange” function Listens to the search textbox when we type and “onQueryTextSubmit” function Listens when we hit search in the keyboard.

PLease leave your comments.

How to use NumberFormat Class in Android? – Rounding a number in android, formatting, getting decimal values etc in android.

package com.coderzheaven.numberformattest;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android. widget. TextView;

public class MainActivity extends Activity {
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        TextView tv = new TextView(this);
        tv.setPadding(10, 10, 10, 10);
		NumberFormat numberFormat  = new DecimalFormat("##");
		String str = numberFormat.format(-01234.567);         // -1235
		tv.setText(str + "\n\n");
 
		str = numberFormat.format(00);                 // 0
		tv.append(str + "\n\n");
 
		numberFormat = new DecimalFormat("##00");
		str = numberFormat.format(0);                 // 00
		tv.append(str + "\n\n");
 
		numberFormat = new DecimalFormat(".00");
		str = numberFormat.format(-.4567);             // -.46
		tv.append(str + "\n\n");
 
		numberFormat = new DecimalFormat("0.000");
		str = numberFormat.format(-.34567);             // -0.346
		tv.append(str + "\n\n");
 
		numberFormat = new DecimalFormat("#.######");
		str = numberFormat.format(-012.34567);         // -12.34567
		tv.append(str + "\n\n");
 
		numberFormat = new DecimalFormat("#.000000");
		str = numberFormat.format(-1234.567);         // -1234.567000
		tv.append(str + "\n\n");
		
		numberFormat = new DecimalFormat("#,###,###");
		str = numberFormat.format(-01234567.890);      // -1 234 568
		tv.append(str + "\n\n");
 
		numberFormat = new DecimalFormat("'text'#");
		str = numberFormat.format(+1234.567);         // text1235		
		tv.append(str + "\n\n");
 
		// Exponential notation
		numberFormat = new DecimalFormat("00.00E0");
		str = numberFormat.format(-012345.67);         // -12.35E2		
		tv.append(str + "\n\n");
		
		// 	set locale format
		// FRANCE  locale
		Locale locale = Locale.FRANCE;
		str = NumberFormat.getNumberInstance(locale).format(-123456.789);  // -123 456,789
		tv.append(str + "\n\n");
		
		setContentView(tv);
		
    }
}

NumberFormat

All about ArrayList – Android.

package com.coderzheaven.arraylistcomplete;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Vector;

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

public class MainActivity extends Activity {

	@SuppressWarnings("unchecked")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		ArrayList<String> al = new ArrayList<String>();

		System.out.println("Initial size of al: " + al.size());

		al.add("C");
		al.add("A");
		al.add("E");
		al.add("B");
		al.add("D");
		al.add("F");
		al.add(1, "A2");

		System.out.println("Size of al after additions: " + al.size());

		System.out.println("Contents of al: " + al);

		al.remove("F");
		al.remove(2);

		System.out.println("Size of al after deletions: " + al.size());
		System.out.println("Contents of al: " + al);

		// *********************************************************//

		List<String> list = new ArrayList<String>();
		list.add("A");
		list.add("B");
		list.add("C");
		List<String> list2 = new ArrayList<String>();
		list2.add("X");
		list2.add("Y");
		list2.add("Z");
		list.addAll(list2);
		list.addAll(1, list2);

		System.out.println(list);

		// **********************************************************//

		ArrayList<String> arrayList = new ArrayList<String>();
		arrayList.add("1");
		arrayList.add("2");
		arrayList.add("3");

		Vector<String> v = new Vector<String>();
		v.add("4");
		v.add("5");

		// insert all elements of Vector to ArrayList at index 1
		arrayList.addAll(1, v);

		for (String str : arrayList)
			System.out.println(str);

		list.clear();

		System.out.println("After Clearing");

		for (String str : arrayList)
			System.out.println(str);

		// ****************************************************************//

		ArrayList myList = new ArrayList(5);
		for (int j = 0; j < 5; j++) {
			myList.add(new Integer(j));
		}
		System.out.println("List contains " + myList.size() + " elements");

		Integer int2 = new Integer(2);
		System.out
				.println("List contains Integer(2): " + myList.contains(int2));
		System.out.println("Integer(2) is at index " + myList.indexOf(int2));

		myList.set(2, new Integer(99));
		System.out.println("Get element at index 2: " + myList.get(2));

		myList.ensureCapacity(15);

		for (int k = myList.size(); k < 25; k++) {
			myList.add(k, new Integer(k));
		}

		System.out.println(myList);

		myList.subList(10, 14).clear();
		myList.trimToSize();

		// ****************************************************************//

		IteratorDemo();

		checkEmpty();
		
		ListIteratorDemo();
		
		

	}

	void IteratorDemo() {
		ArrayList<String> al = new ArrayList<String>();

		al.add("C");
		al.add("A");
		al.add("E");
		al.add("B");
		al.add("D");
		al.add("F");

		System.out.print("Original contents of al: ");
		Iterator<String> itr = al.iterator();
		while (itr.hasNext()) {
			String element = itr.next();
			System.out.print(element + " ");
		}
		System.out.println();

		ListIterator<String> litr = al.listIterator();
		while (litr.hasNext()) {
			String element = litr.next();
			litr.set(element + "+");
		}

		// Now, display the list backwards.
		System.out.print("Modified list backwards: ");
		while (litr.hasPrevious()) {
			String element = litr.previous();
			System.out.print(element + " ");
		}
	}

	void checkEmpty() {
		List list = Arrays.asList(new String[] { "A", "B", "C", "D" });
		System.out.println(list.size());
		System.out.println(list.isEmpty());
	}

	void ListIteratorDemo() {
		ArrayList<String> al = new ArrayList<String>();

		al.add("C");
		al.add("A");
		al.add("E");
		al.add("B");
		al.add("D");
		al.add("F");

		System.out.print("Original contents of al: ");
		Iterator<String> itr = al.iterator();
		while (itr.hasNext()) {
			String element = itr.next();
			System.out.print(element + " ");
		}
		System.out.println();

		ListIterator<String> litr = al.listIterator();
		while (litr.hasNext()) {
			String element = litr.next();
			litr.set(element + "+");
		}

		// Now, display the list backwards.
		System.out.print("Modified list backwards: ");
		while (litr.hasPrevious()) {
			String element = litr.previous();
			System.out.print(element + " ");
		}
	}


}

Download complete tutorial PDF from here.

Please check the LogCat for Output.

Dynamically Adding, Removing, Toggling and Removing all ActionBar Tabs in Android – Part 2?

Hi all..

In today’s post I will show you how to add actionbar tabs dynamically, remove one by one , hide and unhide them, removing all tabs at once etc.

This simple java code does that.

First create a project and in the MainActivity, paste this.

package com.coderzheaven.actionbartabs;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.action_bar_tabs); 
    }

    public void onAddTab(View v) {
        final ActionBar bar = getActionBar();
        final int tabCount = bar.getTabCount();
        final String text = "Tab " + tabCount;
        bar.addTab(bar.newTab()
                .setText(text)
                .setTabListener(new TabListener(new TabContentFragment(text))));
    }

    public void onRemoveTab(View v) {
        final ActionBar bar = getActionBar();
        if(bar.getTabCount() > 0)
        	bar.removeTabAt(bar.getTabCount() - 1);
    }

    public void onToggleTabs(View v) {
        final ActionBar bar = getActionBar();

        if (bar.getNavigationMode() == ActionBar.NAVIGATION_MODE_TABS) {
            bar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
            bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE, ActionBar.DISPLAY_SHOW_TITLE);
        } else {
            bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
            bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
        }
    }

    public void onRemoveAllTabs(View v) {
        getActionBar().removeAllTabs();
    }

    /**
     * A TabListener receives event callbacks from the action bar as tabs
     * are deselected, selected, and reselected. 
     **/
    private class TabListener implements ActionBar.TabListener {
        private TabContentFragment mFragment;

        public TabListener(TabContentFragment fragment) {
            mFragment = fragment;
        }

        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            ft.add(R.id.fragment_content, mFragment, mFragment.getText());
        }

        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
            ft.remove(mFragment);
        }

        public void onTabReselected(Tab tab, FragmentTransaction ft) {
            Toast.makeText(MainActivity.this, "Reselected!", Toast.LENGTH_SHORT).show();
        }
    }

    private class TabContentFragment extends Fragment {
        private String mText;

        public TabContentFragment(String text) {
            mText = text;
        }

        public String getText() {
            return mText;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View fragView = inflater.inflate(R.layout.action_bar_tab_content, container, false);

            TextView text = (TextView) fragView.findViewById(R.id.text);
            text.setText(mText);

            return fragView;
        }
    }
}

You may be getting many errors, we will be resolving all that in just a few minutes.

Now create an xml named “action_bar_tabs.xml” inside the res/layout folder and copy this 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="vertical">
    <FrameLayout android:id="@+id/fragment_content"
                 android:layout_width="match_parent"
                 android:layout_height="0dip"
                 android:layout_weight="1" />
    <LinearLayout android:layout_width="match_parent"
                  android:layout_height="0dip"
                  android:layout_weight="1"
                  android:orientation="vertical">
        <Button android:id="@+id/btn_add_tab"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Add Tab"
                android:onClick="onAddTab" />
        <Button android:id="@+id/btn_remove_tab"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Remove Tab"
                android:onClick="onRemoveTab" />
        <Button android:id="@+id/btn_toggle_tabs"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Toggle Tabs"
                android:onClick="onToggleTabs" />
        <Button android:id="@+id/btn_remove_all_tabs"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Remove All Tabs"
                android:onClick="onRemoveAllTabs" />
    </LinearLayout>
</LinearLayout>

Now create another xml for the tab content and named it “action_bar_tab_content.xml” and copy this code into it.

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/text"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content" />

OK Done. Go on and run it.

ActionBar Tabs

ActionBar Tabs

ActionBar Tabs

ActionBar Tabs

Download Source code from here

Download.

Please leave your valuable comments now