Learn Python


Click to Learn Python3

Monday, November 21, 2011

Running a service in background on Android


Here the code is generate to run some process in background through service. For example we are running the time in background and displaying it in the UI. The service coding will be in a seperate class MyService.java


MyService.java
package com.services.demo;

import java.util.Date;
import android.app.Service; import android.content.Intent; import android.os.Handler; import android.os.IBinder; public class MyService extends Service { public static final String BROADCAST_ACTION = "com.services.demo.ServiceDemoActivity"; private final Handler handler = new Handler(); Intent intent;

int counter = 0; @Override public void onCreate() { // Called on service created intent = new Intent(BROADCAST_ACTION); } @Override

public void onDestroy() { // Called on service stopped }

@Override public void onStart(Intent intent, int startid) { int i = 0; while (i < 101) { if (i > 100) { this.onDestroy(); } else { counter = i; i++; handler.removeCallbacks(sendUpdatesToUI); handler.postDelayed(sendUpdatesToUI, 1 * 1000); // 1 sec }

} } private Runnable sendUpdatesToUI = new Runnable() { public void run() { DisplayLoggingInfo(); handler.postDelayed(this, 1 * 1000); // 1 sec }

}; private void DisplayLoggingInfo() { intent.putExtra("time", new Date().toLocaleString()); intent.putExtra("counter", String.valueOf(counter)); sendBroadcast(intent); }

public static boolean isRunning() { return true; } @Override

public IBinder onBind(Intent intent) { return null; } }

So for starting the service and stopping the service we will be using


Java
startService(new Intent(ServiceDemoActivity.this, MyService.class));
stopService(new Intent(ServiceDemoActivity.this, MyService.class));

For updating the UI we need to use the broadcast service. In that BroadcastReceiver we will update the UI

Java
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateDate(intent);
}

}; private void updateDate(Intent intent) { String time = intent.getStringExtra("time"); TextView date = (TextView) findViewById(R.id.date); date.setText(time); }
In the MyService.java the method DisplayLoggingInfo() will send the broadcast to the activity to update the UI, the UI xml code is
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 >
<TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="@string/hello"
 android:id="@+id/notification"
 />

 <TextView
 android:layout_width="fill_parent" android:id="@+id/date"
 android:layout_height="wrap_content" android:text="" android:gravity="center" android:textSize="20sp" android:padding="20dp"/>
 <Button android:id="@+id/stop" android:text="Stop Service" android:layout_width="wrap_content" android:layout_height="wrap_content" />
</LinearLayout>

If we are opening the application on the first time means, it will be like this

and if we go out and come back to the page means, it will be showing a message like this

and if we stop the service means, it will be showing a message like this



You can download the full source code



Download source


Have a good day.

Monday, November 7, 2011

Show or Hide soft keyboard on opening a dialog or activity in android

For showing the soft keyboard on entering into the activity or to the dialog we can use this coding


Java


InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);



and for hiding the keyboard



Java

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(singleedittext.getWindowToken(),0);



Have a nice day!

Tuesday, November 1, 2011

Animation for view and activities with and without viewflipper in Android

Now we are going to see some animations in android, three types of animation are given on this pack



Yes as shown in the image we are going to see all these types.
First we can see about Animation using ViewFlipper



Here i had added three views in the viewflipper and i had called the animation changes on scrolling using touchevent, the xml section will be like this


viewer.xml

<?xml version="1.0" encoding="utf-8"?>

<ViewFlipper xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_margin="5dip"
android:id="@+id/layoutswitcher"
android:layout_width="fill_parent"
android:layout_height="500dp">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_height="wrap_content"
android:padding="20dip"
android:background="@android:color/background_light"
android:text="Currently you are in Page 1. Scroll right or left to see next page"
android:layout_width="fill_parent"
android:layout_weight="1"
android:textStyle="bold" >
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_height="wrap_content"
android:padding="20dip"
android:background="@android:color/darker_gray"
android:text="Currently you are in Page 2. Scroll right or left to see next page"
android:layout_width="fill_parent"
android:layout_weight="1"
android:textStyle="bold" >
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_height="wrap_content"
android:padding="20dip"
android:background="@android:color/white"
android:text="Currently you are in Page 3. Scroll right or left to see next page"
android:layout_width="fill_parent"
android:layout_weight="1"
android:textStyle="bold" >
</TextView>
</LinearLayout>
</ViewFlipper>



and in the java we need to apply the animation on touchevent as



ViewerEffect.java

package com.animmer;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ViewFlipper;

public class ViewerEffect extends Activity {

private ViewFlipper vf;
private float oldTouchValue;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewer);

vf = (ViewFlipper) findViewById(R.id.layoutswitcher);
}

//for the previous movement
public static Animation inFromRightAnimation() {

Animation inFromRight = new TranslateAnimation(
Animation.RELATIVE_TO_PARENT, +1.0f, Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f
);
inFromRight.setDuration(400);
inFromRight.setInterpolator(new AccelerateInterpolator());
return inFromRight;
}
public static Animation outToLeftAnimation() {
Animation outtoLeft = new TranslateAnimation(
Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, -1.0f,
Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f
);
outtoLeft.setDuration(400);
outtoLeft.setInterpolator(new AccelerateInterpolator());
return outtoLeft;
}
// for the next movement
public static Animation inFromLeftAnimation() {
Animation inFromLeft = new TranslateAnimation(
Animation.RELATIVE_TO_PARENT, -1.0f, Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f
);
inFromLeft.setDuration(400);
inFromLeft.setInterpolator(new AccelerateInterpolator());
return inFromLeft;
}
public static Animation outToRightAnimation() {
Animation outtoRight = new TranslateAnimation(
Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, +1.0f,
Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f
);
outtoRight.setDuration(400);
outtoRight.setInterpolator(new AccelerateInterpolator());
return outtoRight;
}

@Override
public boolean onTouchEvent(MotionEvent touchevent) {
switch (touchevent.getAction())
{
case MotionEvent.ACTION_DOWN:
{
oldTouchValue = touchevent.getX();
break;
}
case MotionEvent.ACTION_UP:
{
float currentX = touchevent.getX();
if (oldTouchValue < currentX)
{
vf.setInAnimation(inFromLeftAnimation());
vf.setOutAnimation(outToRightAnimation());
vf.showNext();
}
if (oldTouchValue > currentX)
{
vf.setInAnimation(inFromRightAnimation());
vf.setOutAnimation(outToLeftAnimation());
vf.showPrevious();
}
break;
}
}
return false;
}
}




Likewise the next is animation between activities



Yes we here we will be giving animation effect between activities
For animation effects we need to put four files in the anim folder, they are slide_in_left, slide_out_left, slide_in_right and slide_out_right.


Java

overridePendingTransition( R.anim.slide_in_left, R.anim.slide_out_left );


The above code is used to move left to right



Java

overridePendingTransition( R.anim.slide_in_right, R.anim.slide_out_right );


The above code is used to move right to left

The final animation technique is to hide and show the views



Here we will be using touch event to assign the animation part, the animation objects will be assigned as shown below


Java

mAnimShow = AnimationUtils.loadAnimation(this, R.anim.slide_in_left);
mAnimHide = AnimationUtils.loadAnimation(this, R.anim.slide_out_right);

mAnimShow.setAnimationListener(new AnimationListener() {

@Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub

}

@Override
public void onAnimationStart(Animation animation) {
overridePendingTransition( R.anim.slide_in_left, R.anim.slide_out_left );

}

@Override
public void onAnimationEnd(Animation animation) {


}

});

mAnimHide.setAnimationListener(new AnimationListener() {

@Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub

}

@Override
public void onAnimationStart(Animation animation) {
overridePendingTransition( R.anim.slide_in_right, R.anim.slide_out_right );

}

@Override
public void onAnimationEnd(Animation animation) {


}

});


The full source code is provided below, you can apply these animation for any other purpose also, the animation technique is same, we need to put this in our logic.


You can download the full source code


Download source


Have a good day.

Tuesday, October 18, 2011

Check whether service is running or not in android application

Using the below given code we can check whether a particular service in our application is running or not


Java

private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ("com.dir.pack.DemoService".equals(service.service.getClassName())) {
return true;
}
}
return false;
}


Here in the if condition we need to give the service file name with the package. So on the checking area you can simply call this function in the if statement like



Java

if(isMyServiceRunning()) {
System.out.println("Service is running");
} else {
System.out.println("Service is not running");
}


Have a nice day

Friday, September 23, 2011

Image and content is populated from Sqlite in Android

In this below application we had populated the listview's data and image from the sqlite



Here we are using a java class for creating the table


PlaceDataSQL.java
package com.data.pack;

package com.data.pack;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/** Helper to the database, manages versions and creation */
public class PlaceDataSQL extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "sample.db";
private static final int DATABASE_VERSION = 1;

private Context context;

public PlaceDataSQL(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE gallery (id varchar(20), image BLOB,caption varchar(160),description varchar(200))");
}

private void versionUpdation(SQLiteDatabase db) {

}

/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* @return true if it exists, false if it doesn't
*/
public boolean checkDataBase(String db) {

SQLiteDatabase checkDB = null;

try {
String myPath = "data/data/com.data.pack/databases/" + db;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);

} catch (SQLiteException e) {

// database does't exist yet.

} catch (Exception e) {

}

if (checkDB != null) {

checkDB.close();

}

return checkDB != null ? true : false;
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion >= newVersion)
return;

if (oldVersion == 1) {
Log.d("New Version", "Datas can be upgraded");
}

Log.d("Sample Data", "onUpgrade : " + newVersion);
}

}



Here in the onCreate function the table is created, here for image we are using blog, so that we can insert the image inside the table itself and the onUpgrade function is used to upgrade the table on the next release, for example you had create an application and published it in market and a guy is using your application, now suddenly you like to add another field on your table means you need to change the " DATABASE_VERSION " to 2 and in the onUpgrade funtion you need to write the alter query there. Likewise i had using a funtion checkDataBase(), this is to check whether the database is exist or not.

Then in the main activity we are calling delete to delete the table content, likewise we will be using a function insertData, inside this function we will be inserting data to the table, like that we will be using getDataAndPopulate(), here we will be retrieving data from the table and displaying in the list.

The main thing is we inserting the image to database for this we are using HttpClient and on the retriving time it is very easy to assign the data, so while calling on the next time we can assign and there is no need of url call for showing image.


SqliteDBActivity.java
package com.data.pack;


package com.data.pack;


import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class SqliteDBActivity extends ListActivity {
private static PlaceDataSQL placeData;
private ArrayList id = new ArrayList();
private ArrayList image = new ArrayList();
private ArrayList caption = new ArrayList();
private ArrayList description = new ArrayList();
private Button populate;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
populate = (Button) findViewById(R.id.populate);
placeData = new PlaceDataSQL(this);

SQLiteDatabase db = placeData.getWritableDatabase();

Cursor cursors = getRawEvents("select * from gallery");

if (cursors.moveToNext()) {
populate.setVisibility(View.GONE);
getDataAndPopulate();
} else {
populate.setVisibility(View.VISIBLE);
}


db.delete("gallery", "id=?", new String[] {
"12" });
populate.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
try {
callInsertion("1","https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjXQTlp6hJ5voBMw9WxJFAFUGW_kUzEeBdoHuRFMkEn8j-mYxrDDmoBizU3Seo1P0BxPre5g2i2JUZi1UpaISGq00rp-h1apLEUxMzVl8WHWQWiZUzhiFRyA63wsvq2tMsN2Ze5LbmhaPk/s1600/twitter_follow.gif","First","This is the first item");
callInsertion("2","https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi6KGi-xGVQybCuzpxCAGMXIKz91RSKaLSCEhUF_yDtzNolI6jAfls0nh_xLEB9wJw0kExxZs0FgRHjxFU2Vm4EDzoFWebBinKNFvi8lc_xhpToMInmiOG71ER8jTSEFySuQ_u1lHgbW6I/s320/seek.JPG","Second","This is the second item");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

getDataAndPopulate();
}
});

}

private void callInsertion(String id, String url, String caption, String description) throws ClientProtocolException, IOException {
DefaultHttpClient mHttpClient = new DefaultHttpClient();
HttpGet mHttpGet = new HttpGet(url);
HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
if (mHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = mHttpResponse.getEntity();
if ( entity != null) {
// insert to database
insertData(id,EntityUtils.toByteArray(entity),caption,description);
}
}
}

private void insertData(String id, byte[] image, String caption, String description) {
SQLiteDatabase db = placeData.getWritableDatabase();
ContentValues values;
values = new ContentValues();
values.put("id", id);
values.put("image", image);
values.put("caption", caption);
values.put("description", description);

db.insert("gallery", null, values);
}

private void getDataAndPopulate() {
id = new ArrayList();
image = new ArrayList();
caption = new ArrayList();
description = new ArrayList();
Cursor cursor = getEvents("gallery");
while (cursor.moveToNext()) {
String temp_id = cursor.getString(0);
byte[] temp_image = cursor.getBlob(1);
String temp_caption = cursor.getString(2);
String temp_description = cursor.getString(3);
id.add(temp_id);
image.add(temp_image);
caption.add(temp_caption);
description.add(temp_description);
}
String[] captionArray = (String[]) caption.toArray(
new String[caption.size()]);

ItemsAdapter itemsAdapter = new ItemsAdapter(
SqliteDBActivity.this, R.layout.item,
captionArray);
setListAdapter(itemsAdapter);
populate.setVisibility(View.GONE);
}


private class ItemsAdapter extends BaseAdapter {
String[] items;

public ItemsAdapter(Context context, int textViewResourceId,
String[] items) {
this.items = items;
}

@Override
public View getView(final int POSITION, View convertView,
ViewGroup parent) {
TextView desc;
TextView cap;
View view = convertView;
ImageView img;
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.item, null);

}
img = (ImageView) view.findViewById(R.id.image);
cap = (TextView) view.findViewById(R.id.caption);

desc = (TextView) view.findViewById(R.id.description);

cap.setText(caption.get(POSITION));
desc.setText(description.get(POSITION));
img.setImageBitmap(BitmapFactory.decodeByteArray(image.get(POSITION), 0, image.get(POSITION).length));


return view;
}

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

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

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

private Cursor getRawEvents(String sql) {
SQLiteDatabase db = (placeData).getReadableDatabase();
Cursor cursor = db.rawQuery(sql, null);

startManagingCursor(cursor);
return cursor;
}

private Cursor getEvents(String table) {
SQLiteDatabase db = (placeData).getReadableDatabase();
Cursor cursor = db.query(table, null, null, null, null, null, null);

startManagingCursor(cursor);
return cursor;
}
}


In this example i had wrote two types of retrieving methods from the table, by writing the query and specifying the table name itself.

You can download the full source code


Download source


Have a good day.

Monday, September 19, 2011

Customize the tab in Android

I had attached two tab examples






First we are going to see about First example


CustomTabActivity.java

package com.customs.tabs;

import com.customs.tabs.R;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;

public class CustomTabActivity extends TabActivity{
private TabHost tabHost;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setTabs();
}

private void setTabs() {
tabHost = getTabHost();

addTab(R.string.tab_1, R.drawable.info);
addTab(R.string.tab_2, R.drawable.info);
addTab(R.string.tab_3, R.drawable.info);
}

private void addTab(int labelId, int drawableId) {
Intent intent = new Intent(this, TabAct.class);
TabHost.TabSpec spec = tabHost.newTabSpec("tab" + labelId);

View tabIndicator = LayoutInflater.from(this).inflate(R.layout.indicator, getTabWidget(), false);

TextView title = (TextView) tabIndicator.findViewById(R.id.title);
title.setText(labelId);
ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
icon.setImageResource(drawableId);

spec.setIndicator(tabIndicator);
spec.setContent(intent);
tabHost.addTab(spec);

}
}


The class extends TabActivity and the header of the tab is provided in seperate activity which is called on the addTab method. The selection / unselection / active colors are mentioned in the indicator xml file in the layout



indicator.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="0dip"
android:layout_height="64dip"
android:layout_weight="1"
android:orientation="vertical"
android:background="@drawable/indicator"
android:padding="5dp">

<ImageView android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
/>

<TextView android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
style="?android:attr/tabWidgetStyle"
/>
</RelativeLayout>


Now we can see the Second example of Tab

Here we are not going to extend the tabactivity, instead of that we can set the tab headers through setting background images or colors using xml and without using xml


CustomTabs.java

package com.customized.tabs;

import com.customized.tabs.R;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.TabHost.TabContentFactory;
import android.widget.TabHost.TabSpec;

public class CustomTabs extends Activity {

private TabHost mTabHost;
private TextView mTabLayout;

private void setupTabHost() {
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
mTabLayout = (TextView) findViewById(R.id.taber);
mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {

@Override
public void onTabChanged(String tabId) {
mTabHost.getTabWidget().getChildAt(0)
.setBackgroundResource(R.drawable.m2);
if ("Tab 1".equals(tabId)) {
mTabHost.getTabWidget().getChildAt(0)
.setBackgroundResource(R.drawable.m1);
mTabLayout.setText("This is Tab 1");
} else if("Tab 2".equals(tabId)) {
mTabLayout.setText("This is Tab 2");
} else {
mTabLayout.setText("This is Tab 3");
}
}
});
}

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

setupTabHost();

//mTabHost.getTabWidget().setDividerDrawable(R.drawable.divider);

setupTab(new TextView(this), "Tab 1");
setupTab(new TextView(this), "Tab 2");
setupTab(new TextView(this), "Tab 3");
}

private void setupTab(final View view, final String tag) {
View tabview = createTabView(mTabHost.getContext(), tag);

TabSpec setContent = mTabHost.newTabSpec(tag).setIndicator(tabview).setContent(new TabContentFactory() {
public View createTabContent(String tag) {return view;}
});
mTabHost.addTab(setContent);
if ("Tab 1".equals(tag))
mTabHost.getTabWidget().getChildAt(0).setBackgroundResource(
R.drawable.m1);


}

private static View createTabView(final Context context, final String text) {
View view = LayoutInflater.from(context).inflate(R.layout.bg, null);
TextView tv = (TextView) view.findViewById(R.id.tabsText);
tv.setText(text);
return view;
}
}


In the above code i had commented the divider between each header, if you need means you can uncomment and i had set a different image for the Tab 1 alone, if you need you can set different images for each tab like that. Then in the bg_selector.xml i had commented the xml files for background color and i had set images for that

You can download the full source code


Download source


Have a good day.

Using Sqlite to populate a ListView in Android

In this below application we had populated the listview using the data from the sqlite



Here we are using a java class for creating the table


PlaceDataSQL.java
package com.data.pack;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/** Helper to the database, manages versions and creation */
public class PlaceDataSQL extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "sample.db";
private static final int DATABASE_VERSION = 1;

private Context context;

public PlaceDataSQL(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE gallery (id varchar(20), image varchar(2000),caption varchar(160),description varchar(200))");
}

private void versionUpdation(SQLiteDatabase db) {

}

/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* @return true if it exists, false if it doesn't
*/
public boolean checkDataBase(String db) {

SQLiteDatabase checkDB = null;

try {
String myPath = "data/data/com.data.pack/databases/" + db;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);

} catch (SQLiteException e) {

// database does't exist yet.

} catch (Exception e) {

}

if (checkDB != null) {

checkDB.close();

}

return checkDB != null ? true : false;
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion >= newVersion)
return;

if (oldVersion == 1) {
Log.d("New Version", "Datas can be upgraded");
}

Log.d("Sample Data", "onUpgrade : " + newVersion);
}

}


Here in the onCreate function the table is created and the onUpgrade function is used to upgrade the table on the next release, for example you had create an application and published it in market and a guy is using your application, now suddenly you like to add another field on your table means you need to change the " DATABASE_VERSION " to 2 and in the onUpgrade funtion you need to write the alter query there. Likewise i had using a funtion checkDataBase(), this is to check whether the database is exist or not.

Then in the main activity we are calling delete to delete the table content, likewise we will be using a function insertData, inside this function we will be inserting data to the table, like that we will be using getDataAndPopulate(), here we will be retrieving data from the table and displaying in the list.



SqliteDBActivity.java
package com.data.pack;


import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class SqliteDBActivity extends ListActivity {
private static PlaceDataSQL placeData;
private ArrayList id = new ArrayList();
private ArrayList image = new ArrayList();
private ArrayList caption = new ArrayList();
private ArrayList description = new ArrayList();
private Button populate;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
populate = (Button) findViewById(R.id.populate);
placeData = new PlaceDataSQL(this);

SQLiteDatabase db = placeData.getWritableDatabase();

Cursor cursors = getRawEvents("select * from gallery");

if (cursors.moveToNext()) {
populate.setVisibility(View.GONE);
getDataAndPopulate();
} else {
populate.setVisibility(View.VISIBLE);
}


db.delete("gallery", "id=?", new String[] {
"12" });
populate.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
insertData("1","https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjXQTlp6hJ5voBMw9WxJFAFUGW_kUzEeBdoHuRFMkEn8j-mYxrDDmoBizU3Seo1P0BxPre5g2i2JUZi1UpaISGq00rp-h1apLEUxMzVl8WHWQWiZUzhiFRyA63wsvq2tMsN2Ze5LbmhaPk/s1600/twitter_follow.gif","First","This is the first item");
insertData("2","https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi6KGi-xGVQybCuzpxCAGMXIKz91RSKaLSCEhUF_yDtzNolI6jAfls0nh_xLEB9wJw0kExxZs0FgRHjxFU2Vm4EDzoFWebBinKNFvi8lc_xhpToMInmiOG71ER8jTSEFySuQ_u1lHgbW6I/s320/seek.JPG","Second","This is the second item");
getDataAndPopulate();
}
});

}

private void insertData(String id, String image, String caption, String description) {
SQLiteDatabase db = placeData.getWritableDatabase();
ContentValues values;
values = new ContentValues();
values.put("id", id);
values.put("image", image);
values.put("caption", caption);
values.put("description", description);

db.insert("gallery", null, values);
}

private void getDataAndPopulate() {
id = new ArrayList();
image = new ArrayList();
caption = new ArrayList();
description = new ArrayList();
Cursor cursor = getEvents("gallery");
while (cursor.moveToNext()) {
String temp_id = cursor.getString(0);
String temp_image = cursor.getString(1);
String temp_caption = cursor.getString(2);
String temp_description = cursor.getString(3);
id.add(temp_id);
image.add(temp_image);
caption.add(temp_caption);
description.add(temp_description);
}
String[] captionArray = (String[]) caption.toArray(
new String[caption.size()]);

ItemsAdapter itemsAdapter = new ItemsAdapter(
SqliteDBActivity.this, R.layout.item,
captionArray);
setListAdapter(itemsAdapter);
populate.setVisibility(View.GONE);
}


private class ItemsAdapter extends BaseAdapter {
String[] items;

public ItemsAdapter(Context context, int textViewResourceId,
String[] items) {
this.items = items;
}

@Override
public View getView(final int POSITION, View convertView,
ViewGroup parent) {
TextView desc;
TextView cap;
View view = convertView;
ImageView img;
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.item, null);

}
img = (ImageView) view.findViewById(R.id.image);
cap = (TextView) view.findViewById(R.id.caption);

desc = (TextView) view.findViewById(R.id.description);

cap.setText(caption.get(POSITION));
desc.setText(description.get(POSITION));
try {
URL url = new URL(image.get(POSITION));
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
BitmapFactory.Options bfOptions = new BitmapFactory.Options();
bfOptions.inDither = false; // Disable Dithering
// mode
bfOptions.inPurgeable = true; // Tell to gc that
// whether it needs
// free memory, the
// Bitmap can be
// cleared
bfOptions.inInputShareable = true; // Which kind of
// reference
// will be used
// to recover
// the Bitmap
// data after
// being clear,
// when it will
// be used in
// the future
bfOptions.inTempStorage = new byte[16 * 1024];
Bitmap bmp = null;
bmp = BitmapFactory.decodeStream(input, null,
bfOptions);
img.setImageBitmap(bmp);
connection.disconnect();
input.close();

} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (IllegalAccessError e) {
} catch (NullPointerException e) {
}

return view;
}

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

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

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

private Cursor getRawEvents(String sql) {
SQLiteDatabase db = (placeData).getReadableDatabase();
Cursor cursor = db.rawQuery(sql, null);

startManagingCursor(cursor);
return cursor;
}

private Cursor getEvents(String table) {
SQLiteDatabase db = (placeData).getReadableDatabase();
Cursor cursor = db.query(table, null, null, null, null, null, null);

startManagingCursor(cursor);
return cursor;
}
}


In this example i had wrote two types of retrieving methods from the table, by writing the query and specifying the table name itself.

You can download the full source code


Download source


Have a good day.

Sunday, July 31, 2011

Creating keystore and google api key for android google maps

Open the command prompt and follow the steps

D:\android-sdk-windows-1.6_r1\tools>keytool -genkey -v -keystore projectkey.keystore -alias aliasname -keyalg RSA -keysize 2048 -validity 15000
Enter keystore password: ------------
What is your first and last name?
[Unknown]: ------------
What is the name of your organizational unit?
[Unknown]: ------------
What is the name of your organization?
[Unknown]: ------------
What is the name of your City or Locality?
[Unknown]: ------------
What is the name of your State or Province?
[Unknown]: ------------
What is the two-letter country code for this unit?
[Unknown]: ------------

D:\android-sdk-windows-1.6_r1\tools>keytool -list -alias aliasname -keystore projectkey.keystore
Enter keystore password:
aliasname, Dec 7, 2010, PrivateKeyEntry,
Certificate fingerprint (MD5): CA:CF:AA:0E:5A:2B:88:C8:64:F1:FA:F7:29:21:50:FF

Using your Certificate fingerprint (MD5) get google api key from this site
http://code.google.com/android/maps-api-signup.html

Saturday, July 30, 2011

How to Install APK Files on Android Emulator using command prompt (cmd) without eclipse

Here we are going to see how to run (install) the apk file to the Android emulator without using eclipse.

Installing in different OS:

1. a Windows, Mac OS X (intel) or Linux (i386) powered computer
2. the Android Software Development Kit (SDK).


You do not need Eclipse or Eclipse-plugin the Android Development Tools (ADT). The last two are required for the software development for Android, but are not necessary for application evaluation on emulator.

First download the Android SDK, which may be obtained here: http://code.google.com/android/download.html

Follow the instruction, described in the topic "Installing SDK" from the Google manual, which is located here: http://code.google.com/android/intro/installing.html#installingsdk or you can go with http://android-codes-examples.blogspot.com/search/label/installation

Steps need to be followed:

Installing the SDK

After downloading the SDK, unpack the .zip archive to a suitable location on your machine. For the rest of this document, we will refer to the directory where you installed the SDK as $SDK_ROOT.

Optionally, you can add $SDK_ROOT/tools and $SDK_ROOT/platform-tools to your path:

On Linux, edit your ~/.bash_profile or ~/.bashrc file. Look for a line that sets the PATH environment variable and add the full path to your $SDK_ROOT/tools to it. If you don't see a line setting the path, you can add one:

export PATH=${PATH}:
On a Mac, look in your home directory for .bash_profile and proceed as for Linux. You can create the .bash_profile, if you haven't already set one up on your machine.
On Windows, right click on My Computer, and select Properties. Under the Advanced tab, hit the Environment Variables button, and in the dialog that comes up, double-click on Path under System Variables, and add the full path to the tools/ directory under $SDK_ROOT to it.

Adding $SDK_ROOT/tools to your path lets you run Android Debug Bridge (adb) and the other command line tools without needing to supply the full path to the tools directory. Note that, if you update your SDK, you should remember to update your PATH settings to point to the new location, if different.


-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-

Now navigate to the $SDK_ROOT/tools directory and execute the file 'emulator.exe'. This is the Android emulator itself. Wait couple of minutes until it loads. Now you must see the home screen of Android - wallpapers with snowy mountains on the background and the navigation bar below.

Enjoyed? Ok! Let's continue. Download and save locally a APK-file which you want to install/evaluate on the emulator. We recommend to save the APK file directly in the $SDK_ROOT/tools directory.

Note: APK probably stands for "Android package". It's an application distribution unit in the Android environment. If you are coming from the Windows Mobile world, think of APK as of CAB-files.

Ok, now start the console ("Start -> Run... -> type 'cmd'" for Windows computers). Type-in the following command: adb install $APK where $APK is the name of the APK file. For example: adb install Snake.apk

If you receive a "path not found" error, then you probably either didn't add path to the $SDK_ROOT/tools directory to your system PATH settings or the application you are trying to install is not in the $SDK_ROOT/tools or $SDK_ROOT/platform-tools directory.

If all went without errors then you should be seeing your newly installed APK on the emulator.

Monday, July 11, 2011

Design a linearlayout or textview and any component in android with border,corner radius and gradient

We can design a linearlayout or relativelayout or framelayout... or even we can design a text view with this coding. The sample is given for linear layout, the result will be like this

here i had given corner radius for left top corner and left bottom corner for the linear layout, and i applied border for whole linearlayout.

For design the layout we need to use this xml file


layout_border.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<stroke android:width="2dp" android:height="2dp"
android:color="#FF0000" />
<solid android:color="#000000" />
<padding android:left="1dp" android:top="1dp" android:right="1dp"
android:bottom="1dp" />

<corners android:radius="1dp" android:bottomRightRadius="5dp"
android:bottomLeftRadius="0dp" android:topLeftRadius="5dp"
android:topRightRadius="0dp" />
</shape>
</item>

</layer-list>


and we need to set the xml file as background for the linear layout as


In the main xml
<LinearLayout android:layout_gravity="center"
android:layout_width="200dp" android:layout_height="200dp" android:background="@drawable/layout_border" />


For gradient effect you can use the below xml, this will not be in the source, you can put this file and set this as background for gradient effect


layout_gradient.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<gradient
android:startColor="#ffa5ba"
android:endColor="#ff92af"
android:angle="150"/>

</shape>


The code is fulling checked so you can run the code after downloading it itself.

You can download the full source code


Download source


Have a good day.

Thursday, April 21, 2011

Google map example in android with info window (Popup) and multiple markers and zoom controls

Through this application we can populate a google map with the info window, zoom controls and marker features. The image of the running application is shown below



First of all, we can run the application with the google api sdk only, we can use from API level 3, but the Google api sdk should be used to run the application.

Custom Linear layout is used on this application




LocationViewers.java

package com.icons.draw.view;

import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ZoomControls;

import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.icons.draw.R;

public class LocationViewers extends LinearLayout {

private MapLocationOverlay overlay;

// Known lat/long coordinates that we'll be using.
private List mapLocations;

public static MapView mapView;

public LocationViewers(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}

public LocationViewers(Context context) {
super(context);
init();
}

public void init() {

setOrientation(VERTICAL);
setLayoutParams(new LinearLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT,android.view.ViewGroup.LayoutParams.FILL_PARENT));
String api = getResources().getString(R.string.map_api_key);
mapView = new MapView(getContext(),api);
mapView.setEnabled(true);
mapView.setClickable(true);
addView(mapView);
overlay = new MapLocationOverlay(this);
mapView.getOverlays().add(overlay);
mapView.getController().setZoom(5);
mapView.getController().setCenter(getMapLocations().get(0).getPoint());
}


public List getMapLocations() {
if (mapLocations == null) {
mapLocations = new ArrayList();
mapLocations.add(new MapLocation("Avinashi road, Coimbatore",11.0138,76.9871));
mapLocations.add(new MapLocation("Marina Beach, Chennai",13.0548,80.2830));
mapLocations.add(new MapLocation("Taj Mahal, New Delhi",28.6353,77.2250));
mapLocations.add(new MapLocation("Meenakshi Temple, Madurai",9.9195,78.1208));
}
return mapLocations;
}

public MapView getMapView() {
return mapView;
}
}



In this LocationViewers.java only we are using the MapView, then this file will be called in the map.xml


map.xml

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

<com.icons.draw.view.LocationViewers
android:id="@+id/map_location_viewer" android:layout_width="fill_parent"
android:layout_height="fill_parent" >


</com.icons.draw.view.LocationViewers>

<ZoomControls android:id="@+id/zoomcontrols"
android:gravity="bottom"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
</FrameLayout>


In the above mentioned xml file we had used the ZoomControls also, this will be given the zoom listener on the java file


DrawIcons.java

package com.icons.draw;

import com.google.android.maps.MapActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ZoomControls;
import com.icons.draw.view.LocationViewers;

public class DrawIcons extends MapActivity {
@Override
public void onCreate(Bundle icicle) {

super.onCreate(icicle);

setContentView(R.layout.map);


ZoomControls zoomControls = (ZoomControls) findViewById(R.id.zoomcontrols);
zoomControls.setOnZoomInClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LocationViewers.mapView.getController().zoomIn();
}
});
zoomControls.setOnZoomOutClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LocationViewers.mapView.getController().zoomOut();
}
});
}

/**
* Must let Google know that a route will not be displayed
*/
@Override
protected boolean isRouteDisplayed() {
return false;
}
}



While pressing the zoom controls plus or minus, this listener will be called and the zoom functionality will be occurs. Then we are going to see two files MapLocation.java and MapLocationOverlay.java, where in the MapLocationOverlay file we will be drawing the marker and the info window for each marker, you can get the code from the zip file below.

The main thing to run the application is adding the internet permission and google library in the AndroidManifest.xml file


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.icons.draw"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".DrawIcons"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-library android:name="com.google.android.maps" />
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk android:minSdkVersion="4" />

</manifest>



The code is fulling checked so you can run the code after downloading it itself.

You can download the full source code


Download source


Have a good day.

Tuesday, April 5, 2011

Animated customized dialog or popup transparent layout with Button and Linear layout gradient effect in android

The image shown below is an example of animated customized popup with transparent layout for button and linearlayout, and the linearlayout and button is given gradient effect


How to get a transparent layout? For that we need to use a transparent class


TransparentPanel.java
package com.popup.design.layers;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.widget.LinearLayout;

public class TransparentPanel extends LinearLayout
{
private Paint innerPaint, borderPaint ;

public TransparentPanel(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}

public TransparentPanel(Context context) {
super(context);
init();
}

private void init() {
innerPaint = new Paint();
innerPaint.setARGB(225, 0, 0, 0);
innerPaint.setAntiAlias(true);

borderPaint = new Paint();
borderPaint.setARGB(255, 0, 0, 0);
borderPaint.setAntiAlias(true);
borderPaint.setStyle(Style.STROKE);
borderPaint.setStrokeWidth(2);
}

public void setInnerPaint(Paint innerPaint) {
this.innerPaint = innerPaint;
}

public void setBorderPaint(Paint borderPaint) {
this.borderPaint = borderPaint;
}

@Override
protected void dispatchDraw(Canvas canvas) {

RectF drawRect = new RectF();
drawRect.set(0,0, getMeasuredWidth(), getMeasuredHeight());

canvas.drawRoundRect(drawRect, 5, 5, innerPaint);
canvas.drawRoundRect(drawRect, 5, 5, borderPaint);

super.dispatchDraw(canvas);
}
}


We need to use this transparentPanel class in the xml file, where we need the transparent layout, in the popup.xml we are using the com.popup.design.layers.TransparentPanel instead of LinearLayout, see in the code


popup.xml

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

<Button android:id="@+id/show_popup_button" android:layout_gravity="bottom"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginBottom="25px" android:text="Show Popup" />

<com.popup.design.layers.TransparentPanel
android:id="@+id/popup_window" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:orientation="vertical"
android:layout_gravity="bottom" android:gravity="left" android:padding="1px"
android:background="@drawable/white">

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:gravity="right"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:background="@drawable/button_bar_gradient">

<Button android:id="@+id/hide_popup_button"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_alignParentRight="true" android:layout_marginTop="5px"
android:layout_marginRight="10px" android:paddingLeft="5px"
android:paddingRight="5px" style="?android:attr/buttonStyleSmall"
android:textStyle="bold" android:textColor="@drawable/white"
android:textSize="12px" android:text=" Close " android:background="@drawable/button_close"/>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="1px" android:layout_marginTop="5px"
android:layout_below="@+id/hide_popup_button" android:background="@drawable/white" />
</RelativeLayout>

<TextView android:id="@+id/location_name"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textStyle="bold" android:textSize="16px" android:textColor="@drawable/white"
android:layout_marginTop="5px" android:layout_marginLeft="5px" />

<TextView android:id="@+id/location_description"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textColor="@drawable/white" android:layout_margin="5px" />

</com.popup.design.layers.TransparentPanel>

</FrameLayout>


Customized Popup is the com.popup.design.layers.TransparentPanel, initially we will hide this layout, and on the button click will show this layout. The java code is as follows


AnimatePopup.java
package com.popup.design;

import com.popup.design.layers.TransparentPanel;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.TextView;

/**
*
* @author http://www.android-codes-examples.blogspot.com/
*
*/
public class AnimatePopup extends Activity {

private Animation animShow, animHide;

@Override
public void onCreate(Bundle icicle) {

super.onCreate(icicle);

setContentView(R.layout.popup);

initPopup();
}

private void initPopup() {

final TransparentPanel popup = (TransparentPanel) findViewById(R.id.popup_window);

// Start out with the popup initially hidden.
popup.setVisibility(View.GONE);


animShow = AnimationUtils.loadAnimation( this, R.anim.popup_show);
animHide = AnimationUtils.loadAnimation( this, R.anim.popup_hide);

final Button showButton = (Button) findViewById(R.id.show_popup_button);
final Button hideButton = (Button) findViewById(R.id.hide_popup_button);
showButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
popup.setVisibility(View.VISIBLE);
popup.startAnimation( animShow );
showButton.setEnabled(false);
hideButton.setEnabled(true);
}});

hideButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
popup.startAnimation( animHide );
showButton.setEnabled(true);
hideButton.setEnabled(false);
popup.setVisibility(View.GONE);
}});


final TextView locationName = (TextView) findViewById(R.id.location_name);
final TextView locationDescription = (TextView) findViewById(R.id.location_description);

locationName.setText("Animated Popup");
locationDescription.setText("Animated popup is created by http://www.android-codes-examples.blogspot.com/"
+ " Transparent layout is used on this example, and animation xml is also used"
+ " on this example. Have a Good day guys.");
}
}


For giving gradient effect we need to use this xml file as the background for the linearlayout or button. The xml file is


button_bar_gradient.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient android:startColor="#C0C0C0"
android:endColor="#505050"
android:angle="90"/>
<corners android:radius="2px" />
</shape>



In the popup.xml we had used the button_bar_gradient as a background. This button_bar_gradient.xml will be in drawable folder.

You can download the full source code


Download source


Have a good day.

Monday, April 4, 2011

ListActivity with remembering the last clicks of the radio button in android

We are going to see about using the ListActivity with radio button example and we are going to see, how to remember the last clicked on this listactivity before going to another activity. The view will be like this

The ListActivity with radio button can be done by using this xml code in the layout


XML

<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#2c0bf9"
android:cacheColorHint="#2c0bf9"
android:drawSelectorOnTop="false"
/>


In the above mentioned xml, we used the android:id as @android:id/list, it is because we are going to use ListActivity. After that we need to insert the code in the java file as


Java

setListAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_single_choice, items));


and for check operation we need to call the selector function, in that itemClicked is a int array where we will be storing whether the row is clicked or not, this will be maintained of item click, the selector and item click functions are follows


Java

private void selector(int first,int total) {
for (int i = 0; i < total; i++) {
View v = getListView().getChildAt(i);
CheckedTextView check = (CheckedTextView) v;
if(itemClicked[first+i]==1)
check.setChecked(true);
else
check.setChecked(false);
}
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
selectFlag = true;
CheckedTextView check = (CheckedTextView) v;
boolean click = !check.isChecked();
check.setChecked(click);
if (click) {
itemClicked[position] = 1;
} else {
itemClicked[position] = 0;
}
}


We need the scroller listener, so that the last checked can be checked while scrolling, for implementing the scroll first we need to implement scroll listener as


Java

public class StoreClicks extends ListActivity implements ListView.OnScrollListener


then in the onscroll we need to call the selector method


Java

@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {

if(visibleItemCount == 6 && !firstTimeFlag) {
selector(0,6);
firstTimeFlag = true;
}
}

@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
switch (scrollState) {
case OnScrollListener.SCROLL_STATE_IDLE:
int first = view.getFirstVisiblePosition();
int last = view.getLastVisiblePosition();
int childCount = view.getChildCount();
selector(first,childCount);
break;

case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
break;

case OnScrollListener.SCROLL_STATE_FLING:
break;
}

}


In the onScroll method the selector will be called only one time, after that onScrollStateChanged selector method will be called, this is why means, for the first page only the items will be visible, we can check or uncheck, so only we are doing like this. The full StoreClicks.java file will be like this


StoreClicks.java

package com.clicks.list;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;

/**
*
* @author http://www.android-codes-examples.blogspot.com/
*
*/

public class StoreClicks extends ListActivity implements
ListView.OnScrollListener {
private static String[] items = { "Joseph", "George", "Mary", "Antony",
"Albert", "Michel", "John", "Abraham", "Mark", "Savior",
"Kristopher", "Thomas", "Williams", "Assisi", "Sebastian",
"Aloysius", "Alex", "Daniel", "Anto", "Alexandar", "Brito",
"Robert", "Jose", "Paul", "Peter" };
private int[] itemClicked = new int[25];
private boolean selectFlag = false; // this will be changed to true if a
private boolean firstTimeFlag = false;
// item is clicked

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button click = (Button) findViewById(R.id.click);

Bundle extras = getIntent().getExtras();
try{
itemClicked = (int[])extras.getIntArray("clicks");
}catch(NullPointerException e){}
if(null == itemClicked)
{
itemClicked = new int[25];
for (int i = 0; i < 25; i++) {
itemClicked[i] = 0;
}
}
click.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
if (selectFlag) {
Intent intent = new Intent(StoreClicks.this, TabPage.class);
Bundle extras = new Bundle();
extras.putIntArray("clicks", itemClicked);
intent.putExtras(extras);
startActivity(intent);
finish();
} else {
Toast.makeText(StoreClicks.this,
"You must select atleast an item",
Toast.LENGTH_SHORT).show();
}
}
});
setListAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_single_choice,
items));
getListView().setOnScrollListener(this);
}

private void selector(int first,int total) {
for (int i = 0; i < total; i++) {
View v = getListView().getChildAt(i);
CheckedTextView check = (CheckedTextView) v;
if(itemClicked[first+i]==1)
check.setChecked(true);
else
check.setChecked(false);
}
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
selectFlag = true;
CheckedTextView check = (CheckedTextView) v;
boolean click = !check.isChecked();
check.setChecked(click);
if (click) {
itemClicked[position] = 1;
} else {
itemClicked[position] = 0;
}
}

@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {

if(visibleItemCount == 6 && !firstTimeFlag) {
selector(0,6);
firstTimeFlag = true;
}
}

@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
switch (scrollState) {
case OnScrollListener.SCROLL_STATE_IDLE:
int first = view.getFirstVisiblePosition();
int last = view.getLastVisiblePosition();
int childCount = view.getChildCount();
selector(first,childCount);
break;

case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
break;

case OnScrollListener.SCROLL_STATE_FLING:
break;
}

}

}



The itemClicked array should be passed in the bundle to the next activity and vice verse to this activity, so that the clicks will be maintained and we can check it explicitly

You can download the full source code


Download source


Have a good day.

Tuesday, March 29, 2011

ListActivity with checkbox using AsyncTask with sleep time example in android

We are going to see about using the ListActivity with checkbox example and we are going to see, how to using the AsyncTask with a good example, here we will be using sleep call, it is optional. The view will be like this



First we can see about using sleep option in android, in our code we used this


Java

for (String item : items) {
publishProgress(item);
SystemClock.sleep(200);
}


Here SystemClock.sleep(200); is used to sleep for a while, for this ListActivity with checkBox or AsyncTask this is not compulsory, this is used in this example for making to know about this sleep option.

The ListActivity with check box can be done by using this xml code in the layout


XML

<ListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false"
/>


like that we need to insert the code in the java file as


Java

setListAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_checked, new ArrayList()));


and for check operation we need to override the function as


Java

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
CheckedTextView check = (CheckedTextView)v;
check.setChecked(!check.isChecked());
}


That will do for showing a List view using the ListActivity, for using the AsyncTask, we need to call the AsyncTask class like


Java

new AddStringTask().execute();


On this call the AsyncTask class will be called


Java

class AddStringTask extends AsyncTask {
@Override
protected Void doInBackground(Void... unused) {
for (String item : items) {
publishProgress(item);
SystemClock.sleep(200);
}

return (null);
}

@Override
protected void onProgressUpdate(String... item) {
((ArrayAdapter) getListAdapter()).add(item[0]);
}

@Override
protected void onPostExecute(Void unused) {
setSelection(3);
Toast.makeText(AsyncTaskDemo.this, "Done!", Toast.LENGTH_SHORT).show();
}
}


The full AsyncTaskDemo.java file will be like this


Java

package com.async.demo;

import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;

/**
*
* @author http://www.android-codes-examples.blogspot.com/
*
*/

public class AsyncTaskDemo extends ListActivity {
private static String[] items = { "Joseph", "George", "Mary", "Antony", "Albert",
"Michel", "John", "Abraham", "Mark", "Savior", "Kristopher",
"Thomas", "Williams", "Assisi", "Sebastian", "Aloysius", "Alex", "Daniel",
"Anto", "Alexandar", "Brito", "Robert", "Jose",
"Paul", "Peter" };

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

setListAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_checked, new ArrayList()));

new AddStringTask().execute();
}

class AddStringTask extends AsyncTask {
@Override
protected Void doInBackground(Void... unused) {
for (String item : items) {
publishProgress(item);
SystemClock.sleep(200);
}

return (null);
}

@Override
protected void onProgressUpdate(String... item) {
((ArrayAdapter) getListAdapter()).add(item[0]);
}

@Override
protected void onPostExecute(Void unused) {
setSelection(3);
Toast.makeText(AsyncTaskDemo.this, "Done!", Toast.LENGTH_SHORT).show();
}
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
CheckedTextView check = (CheckedTextView)v;
check.setChecked(!check.isChecked());
}


}


You can download the full source code


Download source


Have a good day.

Example code for OnKeyDown listener in Android

In this example Toast is shown for the key presses.



The approach is simple, just we need to put this code, thats all


Java

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
switch(keyCode)
{
case KeyEvent.KEYCODE_CAMERA:
Toast.makeText(KeyActions.this, "Pressed Camera Button", Toast.LENGTH_SHORT).show();
return true;
case KeyEvent.KEYCODE_1:
Toast.makeText(KeyActions.this, "Pressed 1", Toast.LENGTH_SHORT).show();
return true;
case KeyEvent.KEYCODE_HOME:
Toast.makeText(KeyActions.this, "Pressed Home Button", Toast.LENGTH_SHORT).show();
return true;

case KeyEvent.KEYCODE_BACK:
Toast.makeText(KeyActions.this, "Pressed Back Button", Toast.LENGTH_SHORT).show();
Intent result = new Intent("Complete");
setResult(Activity.RESULT_OK, result);
finish();
return true;
}

return false;
}


For every key there is the code, after entering the KeyEvent. the eclipse will show the list of codes available.

If you have doubts means

The full source code

Download source


Have a good day.

Wednesday, March 23, 2011

Customized ListView item's selection color can be changed on touching or selecting the item in the list

On selection, on focus, on touch of the items we can change the color of the item, by default android will show a color, we can change it as we like. For that we need this xml to be stored inside the color folder, here only we need mention the colors for each listeners




list_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="false"
android:state_pressed="false"
android:drawable="@color/grey" />
<item android:state_pressed="true"
android:drawable="@color/blue" />
<item android:state_selected="true"
android:state_pressed="false"
android:drawable="@color/blue" />
</selector>



That list_bg.xml will be called in the customized list xml as background


list.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:layout_margin="2dp" android:background="@color/list_bg">

<TextView android:id="@+id/post" android:gravity="center_vertical"
android:layout_width="wrap_content" android:layout_height="50dp"
android:textSize="20sp" android:textColor="#D0640D"
android:layout_toRightOf="@+id/bite_image" />

</RelativeLayout>


This one is the main xml for the Lister.java


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

<ListView android:id="@android:id/list" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:smoothScrollbar="true"
android:background="#fff" android:cacheColorHint="#fff"
android:fastScrollEnabled="false" android:clickable="true"
android:layout_marginBottom="36dp" />

</LinearLayout>



The Lister.java will be like this, the main thing is the list_bg.xml only


Lister.java

package com.list.viewer;

import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class Lister extends ListActivity{

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] captionArray = { "USA","India","England","Russia","Europe","Canada","Srilanka","Singapore","Thailand","Australia"};
ItemsAdapter ItemsAdapter = new ItemsAdapter(
Lister.this, R.layout.list,
captionArray);
setListAdapter(ItemsAdapter);
}


private class ItemsAdapter extends BaseAdapter {
String[] items;

public ItemsAdapter(Context context, int textViewResourceId,
String[] items) {
// super(context, textViewResourceId, items);
this.items = items;
}

// @Override
public View getView(int position, View convertView, ViewGroup parent) {

View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list, null);
}
TextView post = (TextView) v
.findViewById(R.id.post);
post.setText(items[position]);

return v;
}

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

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

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





The full source code

Download source


Have a good day.