Monthly Archives: September 2012

How to find your Google Plus ID

This is so simple

1. Go to your Google + account (https://plus.google.com/).

2. Click on the Profile icon on the Left.

3. If you look at the URL in the address bar, it should look something like this:

https://plus.google.com/104653270154306099169/posts

4. The long numerical string in the URL is your Google+ ID. Here is CoderzHeaven’s from the URL above:

104653270154306099169/

Google + CoderzHeaven

How to get table values from a MySQL database and show it in Android as Tables.?

Here we are accessing a mysql database and get the table values and show it in the Android side as tables.

These are some tutorials that I have posted on connection with php and getting tablevalues.
1. Android phpmySQL connection redone.

2. Simplest Lazy Loading ListView Example in Android with data populated from a MySQL database using php.

Here we have 3 classes
1. GetDataFromDB.java – Gets value from DB in the form of JSON.
2. Users.java _ Class which holds the one row table object.
3. MainActivity.java _ Which implements these classes and show the tables.

MainActivity.java

package com.coderzheaven.gettablefromphp;

import java.util.ArrayList;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.   graphics.   Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;

public class MainActivity extends Activity {

	String data = "";
	TableLayout tl;
	TableRow tr;
	TextView label;

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

		tl = (TableLayout) findViewById(R.id.maintable);

		final GetDataFromDB getdb = new GetDataFromDB();
		new Thread(new Runnable() {
			public void run() {
				data = getdb.getDataFromDB();
				System.out.println(data);
				
				runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						ArrayList<Users> users = parseJSON(data);
						addData(users);						
					}
				});
				
			}
		}).start();
	}

	public ArrayList<Users> parseJSON(String result) {
		ArrayList<Users> users = new ArrayList<Users>();
		try {
			JSONArray jArray = new JSONArray(result);
			for (int i = 0; i < jArray.length(); i++) {
				JSONObject json_data = jArray.getJSONObject(i);
				Users user = new Users();
				user.setId(json_data.getInt("id"));
				user.setName(json_data.getString("name"));
				user.setPlace(json_data.getString("place"));
				users.add(user);
			}
		} catch (JSONException e) {
			Log.e("log_tag", "Error parsing data " + e.toString());  
		}
		return users;
	}

	void addHeader(){
		/** Create a TableRow dynamically **/
		tr = new TableRow(this);

		/** Creating a TextView to add to the row **/
		label = new TextView(this);
		label.setText("User");
		label.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT));
		label.setPadding(5, 5, 5, 5);
		label.setBackgroundColor(Color.RED);
		LinearLayout Ll = new LinearLayout(this);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT);
		params.setMargins(5, 5, 5, 5);
		//Ll.setPadding(10, 5, 5, 5);
		Ll.addView(label,params);
		tr.addView((View)Ll); // Adding textView to tablerow.

		/** Creating Qty Button **/
		TextView place = new TextView(this);
		place.setText("Place");
		place.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT));
		place.setPadding(5, 5, 5, 5);
		place.setBackgroundColor(Color.RED);
		Ll = new LinearLayout(this);
		params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT);
		params.setMargins(0, 5, 5, 5);
		//Ll.setPadding(10, 5, 5, 5);
		Ll.addView(place,params);
		tr.addView((View)Ll); // Adding textview to tablerow.

		 // Add the TableRow to the TableLayout
        tl.addView(tr, new TableLayout.LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
	}
	
	@SuppressWarnings({ "rawtypes" })
	public void addData(ArrayList<Users> users) {

		addHeader();
		
		for (Iterator i = users.iterator(); i.hasNext();) {

			Users p = (Users) i.next();

			/** Create a TableRow dynamically **/
			tr = new TableRow(this);

			/** Creating a TextView to add to the row **/
			label = new TextView(this);
			label.setText(p.getName());
			label.setId(p.getId());
			label.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT));
			label.setPadding(5, 5, 5, 5);
			label.setBackgroundColor(Color.GRAY);
			LinearLayout Ll = new LinearLayout(this);
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
					LayoutParams.WRAP_CONTENT);
			params.setMargins(5, 2, 2, 2);
			//Ll.setPadding(10, 5, 5, 5);
			Ll.addView(label,params);
			tr.addView((View)Ll); // Adding textView to tablerow.

			/** Creating Qty Button **/
			TextView place = new TextView(this);
			place.setText(p.getPlace());
			place.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT));
			place.setPadding(5, 5, 5, 5);
			place.setBackgroundColor(Color.GRAY);
			Ll = new LinearLayout(this);
			params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
					LayoutParams.WRAP_CONTENT);
			params.setMargins(0, 2, 2, 2);
			//Ll.setPadding(10, 5, 5, 5);
			Ll.addView(place,params);
			tr.addView((View)Ll); // Adding textview to tablerow.

			 // Add the TableRow to the TableLayout
            tl.addView(tr, new TableLayout.LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT));
		}
	}
}

GetDataFromDB.java

package com.coderzheaven.gettablefromphp;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

public class GetDataFromDB {

	public String getDataFromDB() {
		try {

			HttpPost httppost;
			HttpClient httpclient;
			httpclient = new DefaultHttpClient();
			httppost = new HttpPost(
					"http://10.0.2.2/test/GetUsers.php"); // change this to your URL.....
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			final String response = httpclient.execute(httppost,
					responseHandler);
			
			return response.trim();

		} catch (Exception e) {
			System.out.println("ERROR : " + e.getMessage());
			return "error";
		}
	}
}

Users.java

package com.coderzheaven.gettablefromphp;

public class Users {

	int id;
	String name;
	String place;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPlace() {
		return place;
	}
	public void setPlace(String place) {
		this.place = place;
	}
	
}

The activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ScrollView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fillViewport="true"
    android:    scrollbars  =  "none"
    android:layout_below="@+id/textView1">
        <TableLayout
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:stretchColumns="1,0,0"
            android:id="@+id/maintable" >
        </TableLayout>
    </ScrollView>
    
</RelativeLayout>

The server Side php.

GetUsers.php

<?php

	mysql_connect("localhost","root",""); // host, username, password...
	mysql_select_db("testdb"); // db name...
	 
	$q=mysql_query("SELECT * FROM users");
	while($row=mysql_fetch_assoc($q))
			$json_output[]=$row;
	 
	print(json_encode($json_output));
	 
	mysql_close();
	
?>

Table Php Android

Table Php Android

Download the complete source code from here.

Download
.

Join the Forum discussion on this post

Simplest Lazy Loading ListView Example in Android with data populated from a MySQL database using php.

Hello all…

You may have seen many implementations of Lazy Loading ListView.
Today I will show you my method to create Lazy Loading ListViews.

I dont know whether it can be any more simple than this.

In this I am using AsyncTask to download each image.

So we will start.

Here we have 6 classes.

1. MainPage – This is our main activity that loads the ListView.
2. GetDataFromDB – This class get the image urls and it’s description as a string from the DB server and return that string.
Then we will split that string to seperate the urls and description and then set it to listview.
3. MyCustomArrayAdapter – Custom adapter for the ListView.
4. Model _ this class creates the object to be set for the ListView for each row.
5. PbAndImage – This class has an imageView and ProgressBar to send to the Asynctask.
6. DownloadImageTask – This class Asynchronously downloads the image.

At last the PHP Script which simple echoes the string containing the URLS and description of the image.

Here is the PHP Script.

getImageUrlsAndDescription.php

<?php
// get these values from your DB.
echo 	"http://coderzheaven.com/sample_folder/android_1.png,ANDROID0 ## 
		http://coderzheaven.com/sample_folder/coderzheaven.png,ANDROID1 ## 
		http://coderzheaven.com/sample_folder/coderzheaven.png,ANDROID2 ## 
		http://coderzheaven.com/sample_folder/coderzheaven.png,ANDROID3 ## 
		http://coderzheaven.com/sample_folder/android_1.png,ANDROID4 ## 
		http://coderzheaven.com/sample_folder/coderzheaven.png,ANDROID5 ## 
		http://coderzheaven.com/sample_folder/coderzheaven.png,ANDROID6 ## 
		http://coderzheaven.com/sample_folder/android_1.png,ANDROID7 ## 
		http://coderzheaven.com/sample_folder/coderzheaven.png,ANDROID8 ## 

http://coderzheaven.com/sample_folder/coderzheaven.png,ANDROID9";

?>

So we will start.

MainPage.java


package com.coderzheaven.lazyloadinglistwithphpconnection;

import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public     class     MainPage    extends ListActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.   layout.    contacts_list);

		final List<Model> list = new ArrayList<Model>();
		
		/** This block is for getting the image url to download from the server **/
		final GetDataFromDB getvalues = new GetDataFromDB();
		
		final ProgressDialog dialog = ProgressDialog.show(MainPage.this,
				"", "Gettting values from DB", true);
		new    Thread   (new Runnable() {
			public void run() {
				String response = getvalues.getImageURLAndDesciptionFromDB();
				System.out.println("Response : " + response);
				
				dismissDialog(dialog);
				if (!response.equalsIgnoreCase("")) {
					if (!response.equalsIgnoreCase("error")) {
						dismissDialog(dialog);
						
						// Got the response, now split it to get the image Urls and description
						String all[] = response.split("##"); 
						for(int k = 0; k < all.length; k++){
							String urls_and_desc[] = all[k].split(","); //  urls_and_desc[0] contains image url and [1] -> description.
							list.add(get(urls_and_desc[1],urls_and_desc[0]));
						}
					}
					
				} else {
					dismissDialog(dialog);
				}
			}
		}).start();
		/*************************** GOT data from Server ********************************************/

		ArrayAdapter<Model> adapter = new MyCustomArrayAdapter(this, list);
		setListAdapter(adapter);
	}

	public void dismissDialog(final ProgressDialog dialog){
		runOnUiThread(new Runnable() {
			public void run() {
				dialog.dismiss();
			}
		});
	}
	private Model get(String s, String url) {
		return new Model(s, url);
	}

}

GetDataFromDB.java

package com.coderzheaven.lazyloadinglistwithphpconnection;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

public class GetDataFromDB {

	public String getImageURLAndDesciptionFromDB() {
		try {

			HttpPost httppost;
			HttpClient httpclient;
			httpclient = new DefaultHttpClient();
			httppost = new HttpPost(
					"http://10.0.2.2/test/getImageUrlsAndDescription.php"); // change this to your URL.....
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			final String response = httpclient.execute(httppost,
					responseHandler);
			
			return response;

		} catch (Exception e) {
			System.out.println("ERROR : " + e.getMessage());
			return "error";
		}
	}
}

Model.java

package com.coderzheaven.lazyloadinglistwithphpconnection;

public class Model {
	 
    private String name;
    private String url;
    
    public Model(String name, String url) {
        this.name = name;
        this.url = url;
    }

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getURL() {
		return url;
	}

	public void setURL(String url) {
		this.url = url;
	}
}

MyCustomArrayAdapter.java

package com.coderzheaven.lazyloadinglistwithphpconnection;

import java.util.List;
import android.app.Activity;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MyCustomArrayAdapter extends ArrayAdapter<Model> {

	private final Activity context;
	private final List<Model> list;

	public MyCustomArrayAdapter(Activity context, List<Model> list) {
		super(context, R.layout.list_layout, list);
		this.context = context;
		this.list = list;
	}

	static class ViewHolder {
		protected TextView text;
		protected ImageView image;
		protected ProgressBar pb;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view = null;
		if (convertView == null) {
			LayoutInflater inflator = context.getLayoutInflater();
			view = inflator.inflate(R.layout.list_layout, null);
			final ViewHolder viewHolder = new ViewHolder();
			viewHolder.text = (TextView) view.findViewById(R.id.label);
			viewHolder.text.setTextColor(Color.BLACK);
			viewHolder.image = (ImageView) view.findViewById(R.id.image);
			viewHolder.image.setVisibility(View.GONE);
			viewHolder.pb = (ProgressBar) view.findViewById(R.id.progressBar1);
			view.setTag(viewHolder);
		} else {
			view = convertView;
		}
		ViewHolder holder = (ViewHolder) view.getTag();
		holder.text.setText(list.get(position).getName());
		holder.image.setTag(list.get(position).getURL());
		holder.image.setId(position);
		PbAndImage pb_and_image = new PbAndImage();
		pb_and_image.setImg(holder.image);
		pb_and_image.setPb(holder.pb);
    	new DownloadImageTask().execute(pb_and_image);
		return view;
	}
}

PbAndImage.java

package com.coderzheaven.lazyloadinglistwithphpconnection;

import android.widget.ImageView;
import android.widget.ProgressBar;

public class PbAndImage {
	
	private ImageView img;
	private ProgressBar pb;

	public ImageView getImg() {
		return img;
	}

	public void setImg(ImageView img) {
		this.img = img;
	}

	public ProgressBar getPb() {
		return pb;
	}

	public void setPb(ProgressBar pb) {
		this.pb = pb;
	}

}

DownloadImageTask.java

package com.coderzheaven.lazyloadinglistwithphpconnection;

import java.io.InputStream;
import java.net.URL;
import com.coderzheaven.lazyloadinglistwithphpconnection.PbAndImage;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

public class DownloadImageTask extends AsyncTask<PbAndImage, Void, Bitmap> {

	ImageView imageView = null;
	ProgressBar pb = null;

	protected Bitmap doInBackground(PbAndImage... pb_and_images) {
		this.imageView = (ImageView)pb_and_images[0].getImg();
		this.pb = (ProgressBar)pb_and_images[0].getPb();
		return getBitmapDownloaded((String) imageView.getTag());
	}

	protected void onPostExecute(Bitmap result) {
		System.out.println("Downloaded " + imageView.getId());
		imageView.setVisibility(View.VISIBLE); 
		pb.setVisibility(View.GONE);  // hide the progressbar after downloading the image.
		imageView.setImageBitmap(result); //set the bitmap to the imageview.
	}

	/** This function downloads the image and returns the Bitmap **/
	private Bitmap getBitmapDownloaded(String url) {
		System.out.println("String URL " + url);
		Bitmap bitmap = null;
		try {
			bitmap = BitmapFactory.decodeStream((InputStream) new URL(url)
					.getContent());
			bitmap = getResizedBitmap(bitmap, 50, 50);
			return bitmap;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bitmap;
	}
	
	/** decodes image and scales it to reduce memory consumption **/
	public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
        int width = bm.getWidth();
        int height = bm.getHeight();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // CREATE A MATRIX FOR THE MANIPULATION
        Matrix matrix = new Matrix();
        // RESIZE THE BIT MAP
        matrix.postScale(scaleWidth, scaleHeight);
        // RECREATE THE NEW BITMAP
        Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
        return resizedBitmap;
    }
}

And the Most important thing – DONT FORGET TO ADD THE INTERNET PERMISSION ON YOUR MANIFEST FILE.

 <uses-permission android:name="android.permission.INTERNET"/>

These are the layout files.

contacts_list.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:layout_margin="10dp" >
    
  <ListView
            android:id="@id/android:list"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:dividerHeight="1dp"
            android:cacheColorHint="#0000"
            android:clipToPadding="true"
            android:layout_margin="5dp"
            android:soundEffectsEnabled="true"
            android:scrollbars="none"
            android:layout_weight="1">
    </ListView>

</LinearLayout>

list_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal">
    
    <ProgressBar
        android:id="@+id/progressBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    
     <ImageView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:layout_margin="10dp"
        android:id="@+id/image"
        android:contentDescription="@drawable/ic_launcher">        
    </ImageView>
    
    <TextView 
        android:text="@+id/label" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:id="@+id/label"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="5dp"
        android:textStyle="bold"
        android:textSize="20sp">        
    </TextView>
   
</LinearLayout>

Lazy Loading Image

Lazy Loading Image

Lazy Loading Image

Lazy Loading Image

Lazy Loading Image

Please leave your comments on this post.

Join the Forum discussion on this post

How to show error in an EditText using setError() in Android?

We will go straight to the code.

package com.coderzheaven.seterror;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

	 @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.activity_main);
	        Button btn =(Button)findViewById(R.id.button1);
	        btn.setOnClickListener(new OnClickListener() {
	            
	            @Override
	            public void onClick(View v) {
	                 EditText edittext =(EditText)findViewById(R.id.editText1);
	                if(edittext.getText().length()==0){
	                    edittext.setError("Field cannot be left blank.");
	                }
	            }
	        });
	    }
}

This is the layout containing the EditText and the Button.

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

    <EditText
        android:id="@+id/editText1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/editText1"
        android:text="Check" />

</RelativeLayout>

SetError Android

How will you create a custom Notification in Android with a custom Layout?

This sample application does that.

First create an xml for your notification.

custom_notification.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp" >
    <ImageView android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="10dp" />
    <TextView android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/image"
        style="Custom Notification Title" />
    <TextView android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/image"
        android:layout_below="@id/title"
        style="Custom Notification Text" />
</RelativeLayout>

Now the java code.

package com.coderzheaven.customnotification;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.widget.RemoteViews;

public class MainActivity extends Activity {

    @SuppressWarnings("deprecation")
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        int icon = R.drawable.ic_launcher;
        long when = System.currentTimeMillis();
        Notification notification = new Notification(icon, "Custom Notification", when);

    	NotificationManager mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    	
        RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification);
        contentView.setImageViewResource(R.id.image, R.drawable.ic_launcher);
        contentView.setTextViewText(R.id.title, "Custom notification");
        contentView.setTextViewText(R.id.text, "This is a custom layout");
        notification.contentView = contentView;
        
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        notification.contentIntent = contentIntent;
        
        notification.flags |= Notification.FLAG_NO_CLEAR; //Do not clear the notification
        notification.defaults |= Notification.DEFAULT_LIGHTS; // LED
        notification.defaults |= Notification.DEFAULT_VIBRATE; //Vibration
        notification.defaults |= Notification.DEFAULT_SOUND; // Sound
        
        mNotificationManager.notify(1, notification);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

Custom Notification

How to create a Scrolling Text (marquee) in android using TextView?

OK At first we will create the XML that contains a TextView.

marqueetext.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

   <TextView
    android:text="Really Long Scrolling Text Goes Here.... ..... ............ .... ...."
    android:singleLine="true"
    android:ellipsize="marquee"
    android:marqueeRepeatLimit="marquee_forever"
    android:scrollHorizontally="true"
    android:id="@+id/TextView03"
    android:padding="5dip" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" />
   
</RelativeLayout>

Now the java code

package com.example.marqueetext;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;

public class Marqueetext extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.marqueetext);
        
        TextView tv = (TextView) this.findViewById(R.id.TextView03);  
        tv.setSelected(true);  // Set focus to the textview
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.marqueetext, menu);
        return true;
    }
}

Note : The XMl alone will not create the marquee. For that the most important thing is to do this in java code.

 tv.setSelected(true);  // Set focus to the textview

Now run the project and see the result.

Marquee

Marquee

How to Uninstall Avast Anti Theft for Android?

If you have installed Avast and the Avast anti theft application on your Android and decide you no longer need it, you may find it difficult to remove. It is protected so you first need to remove it’s protection. Here’s how to do it.
First
Goto Settings >> Security >> Select Device Administrators – you can then remove the tick mark alongside the app.
Now again Got To Apps-> Uninstall Avast and the Anti-theft.

How to create a blinking text in Android?

Hello everyone…

Here I am explaining two methods on how to create a blinking textview in Android.

One with the help of Animation class and other with a Logic.

Now let’s see that..

Place a textview with an id of “tv” in your layout and attempt this.

package com.coderzheaven.blinktext;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        blinkText();
        //blinkText2();
    }
    
    private void blinkText(){
        final Handler handler = new Handler();
        new Thread(new Runnable() {
            @Override
            public void run() {
            int timeToBlink = 1000;    //in ms
            try{
            	Thread.sleep(timeToBlink);
        	}catch (Exception e) {
        		
        	}
            handler.post(new Runnable() {
                @Override
                    public void run() {
                    TextView txt = (TextView) findViewById(R.id.tv);
                    if(txt.getVisibility() == View.VISIBLE){
                        txt.setVisibility(View.INVISIBLE);
                    }else{
                        txt.setVisibility(View.VISIBLE);
                    }
                    blinkText();
                }
                });
            }}).start();
   }
    
    public void blinkText2(){
    	TextView myText = (TextView) findViewById(R.id.tv );

    	Animation anim = new AlphaAnimation(0.0f, 1.0f);
    	anim.setDuration(50); //You can manage the time of the blink with this parameter
    	anim.setStartOffset(20);
    	anim.setRepeatMode(Animation.REVERSE);
    	anim.setRepeatCount(Animation.INFINITE);
    	myText.startAnimation(anim);
    }
   

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    
}

Download the complete android source code from below.

Download.

How to create a Slide from Left animation while deleting a row from a ListView in Android?

Hello all……

I have written a lost of posts on Listviews. You can see that by just searching Listviews in my site. Today I will show you how to create a slide out animation while we delete a row from a ListView.

So this is the xml that contains the ListView. Let it be in the main.xml

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">
  
	<ListView android:layout_width="fill_parent" 
	  android:layout_height="fill_parent" 
	  android:id="@+id/mainListView">
	</ListView>
	
</LinearLayout>

Create another file inside the layout folder named “simplerow.xml”.

simplerow.xml

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/rowTextView" 
 android:layout_width="fill_parent" 
 android:layout_height="wrap_content"
 android:padding="10dp"
 android:textSize="16sp" >
</TextView>

OK our xml part is over. Now the java part.

This is the main java file that implements this xml.

“SimpleListViewActivity.java”

package com.coderzheaven.pack;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class SimpleListViewActivity extends Activity {
  
  private ListView mainListView ;
  private ArrayAdapter<String> listAdapter ;
   ArrayList<String> all_planets = 
       new ArrayList<String>(){      
           private static final long serialVersionUID = -1773393753338094625L;
           {
               add("Mercury ");
               add("Venus "); 
               add("Earth"); 
               add("Mars"); 
               add("Jupiter"); 
               add("Saturn"); 
               add("Uranus"); 
               add("Neptune"); 
               add("Pluto"); 
           }
   };
   
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);    
  
    mainListView = (ListView) findViewById( R.id.mainListView );

    listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, all_planets);

    mainListView.setAdapter( listAdapter );  
    
    mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View rowView, int positon,long id) {
            Toast.makeText(rowView.getContext(), ""+positon, Toast.LENGTH_LONG).show();
            removeListItem(rowView,positon);
        }
    });
    
  }
  
  protected void removeListItem(View rowView, final int positon) {

      final Animation animation = AnimationUtils.loadAnimation(SimpleListViewActivity.this,android.R.anim.slide_out_right); 
      rowView.startAnimation(animation);
      Handler handle = new Handler();
      handle.postDelayed(new Runnable() {

		@Override
          public void run() {
        	  all_planets.remove(positon);
              listAdapter.notifyDataSetChanged();
              animation.cancel();
          }
      },1000);

  }

}

OK Done. Now run it and see the result.

Slide delete

Slide delete

Slide delete

Join the Forum discussion on this post

Download.

How to read and write files to SDCARD and application SandBox in Android – A complete example?

Here is a complete example of How to read and write files to SDCARD and application SandBox in Android.

First create a new project and inside the mainActivity paste this code.

package com.coderzheaven.filesexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

	EditText edittext;
	Button b1, b2, b3, b4;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        edittext = (EditText)findViewById(R.id.ed);
        edittext.setLines(10);
        b1 = (Button)findViewById(R.id.button1);
        b2 = (Button)findViewById(R.id.button2);
        b3 = (Button)findViewById(R.id.button3);
        b4 = (Button)findViewById(R.id.button4);
        
        b1.setOnClickListener(this);
        b2.setOnClickListener(this);
        b3.setOnClickListener(this);
        b4.setOnClickListener(this);        
        
    }
	@Override
	public void onClick(View v) {
		int id = v.getId();
		MyFile file = new MyFile(v.getContext());
		
		switch(id){
			case R.id.button1:
				if(!edittext.getText().toString().trim().equals("")){
					file.writeToSD(edittext.getText().toString());
				}else{
					Toast.makeText(v.getContext(), "Please enter some contents for the file", Toast.LENGTH_LONG).show();
				}
				break;
				
			case R.id.button2:
				edittext.setText(file.readFromSD());
				break;
			
			case R.id.button3:
				if(!edittext.getText().toString().trim().equals("")){
					file.writeToSandBox(edittext.getText().toString());
				}else{
					Toast.makeText(v.getContext(), "Please enter some contents for the file", Toast.LENGTH_LONG).show();
				}
				break;
				
			case R.id.button4:
				edittext.setText(file.readFromSandBox());
				break;
		}
		
		
		
	}

}

Now create another class named MyFile.java and copy this code into it.

package com.coderzheaven.filesexample;

import java.io. BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Environment;
import android.util.Log;

public class MyFile {

	String TAG = "MyFile";
	Context context;
	public MyFile(Context context){
		this.context = context;
	}
	
	public Boolean writeToSD(String text){
		Boolean write_successful = false;
		 File root=null;  
	        try {  
	            // check for SDcard   
	            root = Environment.getExternalStorageDirectory();  
	            Log.i(TAG,"path.." +root.getAbsolutePath());  
	  
	            //check sdcard permission  
	            if (root.canWrite()){  
	                File fileDir = new File(root.getAbsolutePath());  
	                fileDir.mkdirs();  
	  
	                File file= new File(fileDir, "samplefile.txt");  
	                FileWriter filewriter = new FileWriter(file);  
	                BufferedWriter out = new BufferedWriter(filewriter);  
	                out.write(text);  
	                out.close();  
	                write_successful = true;
	            }  
	        } catch (IOException e) {  
	            Log.e("ERROR:---", "Could not write file to SDCard" + e.getMessage());  
	            write_successful = false;
	        }  
		return write_successful;
	}
	
	public String readFromSD(){
		File sdcard = Environment.getExternalStorageDirectory();
		File file = new File(sdcard,"samplefile.txt");
		StringBuilder text = new StringBuilder();
		try {
		    BufferedReader br = new BufferedReader(new FileReader(file));
		    String line;
		    while ((line = br.readLine()) != null) {
		        text.append(line);
		        text.append('\n');
		    }
		}
		catch (IOException e) {
		}
		return text.toString();
	}

	@SuppressLint("WorldReadableFiles")
	@SuppressWarnings("static-access")
	public Boolean writeToSandBox(String text){
		Boolean write_successful = false;
		try{
			FileOutputStream fOut = context.openFileOutput("samplefile.txt",
					context.MODE_WORLD_READABLE);
			OutputStreamWriter osw = new OutputStreamWriter(fOut); 
			osw.write(text);
			osw.flush();
			osw.close();
		}catch(Exception e){
			write_successful = false;
		}
		return write_successful;
	}
	public String readFromSandBox(){
		String str ="";
		String new_str = "";
		try{
			FileInputStream fIn = context.openFileInput("samplefile.txt");
            InputStreamReader isr = new InputStreamReader(fIn);
            BufferedReader br=new BufferedReader(isr);
           
			while((str=br.readLine())!=null)
            {
				new_str +=str;
				System.out.println(new_str);
            }            
		}catch(Exception e)
		{			
		}
		return new_str;
	}
}

Now the layout for the xml file.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/ed"
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent"
		android:lines="5" android:gravity="top|left" android:inputType="textMultiLine"
		android:scrollHorizontally="false" 
		android:minWidth="10.0dip"
		android:maxWidth="5.0dip"
        android:layout_weight="1"/>


    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Write File to SDCARD" />
    
    <Button
        android:id="@+id/button2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Read File from SDCARD" />
    
    <Button
        android:id="@+id/button3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Write File to Application SandBox" />
    
    <Button
        android:id="@+id/button4"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Read File from Application SandBox" />

</LinearLayout>

Note you should give this permission in the AndroidManifest file.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

OK Done. Now run the project.

To view the files

1. To see the SDCARD
Open File explorer -> expand sdcard (or mnt/sdcard).
2. To see the Application SANDBOX
Open File explorer -> expand data/data/your_package_name/files.

Files Example

Download
.

Please leave your valuable comments on this post.

Join the Forum discussion on this post

How to show two different DatepickerDialogs on same activity with only one listener function in android?

In android for each time picker Dialog we can associate with a dialog. So with this dialog and a global variable we can have any number of Dialog listeners. Here is the sample java code.

This is the layout file – 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" >

    <Button
        android:id="@+id/btnChangeDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Date" />
    
     <Button
        android:id="@+id/btnChangeDate2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Date2" />

    <TextView
        android:id="@+id/lblDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Current Date (M-D-YYYY): "
        android:textAppearance="?android:attr/textAppearanceLarge" />
  
    <TextView
        android:id="@+id/tvDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge" />
    
     <TextView
        android:id="@+id/tvDate2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

MyAndroidAppActivity .java


import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class MyAndroidAppActivity extends Activity {

	private TextView tvDisplayDate, tvDisplayDate2;
	private DatePicker dpResult;
	private Button btnChangeDate, btnChangeDate2;

	private int year;
	private int month;
	private int day;

	static final int DATE_DIALOG_ID = 1;
	static final int DATE_DIALOG_ID2 = 2;
	int cur = 0;

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

		setCurrentDateOnView();
		addListenerOnButton();

	}

	// display current date
	public void setCurrentDateOnView() {

		tvDisplayDate = (TextView) findViewById(R.id.tvDate);
		tvDisplayDate2 = (TextView) findViewById(R.id.tvDate2);

		final Calendar c = Calendar.getInstance();
		year = c.get(Calendar.YEAR);
		month = c.get(Calendar.MONTH);
		day = c.get(Calendar.DAY_OF_MONTH);

		// set current date into textview
		tvDisplayDate.setText(new StringBuilder()
				// Month is 0 based, just add 1
				.append(month + 1).append("-").append(day).append("-")
				.append(year).append(" "));

		tvDisplayDate2.setText(tvDisplayDate.getText().toString());
	}

	public void addListenerOnButton() {

		btnChangeDate = (Button) findViewById(R.id.btnChangeDate);

		btnChangeDate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				showDialog(DATE_DIALOG_ID);

			}

		});
		btnChangeDate2 = (Button) findViewById(R.id.btnChangeDate2);

		btnChangeDate2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
				showDialog(DATE_DIALOG_ID2);

			}

		});

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		
		case DATE_DIALOG_ID:
			System.out.println("onCreateDialog  : " + id);
			cur = DATE_DIALOG_ID;
			// set date picker as current date
			return new DatePickerDialog(this, datePickerListener, year, month,
					day);
		case DATE_DIALOG_ID2:
			cur = DATE_DIALOG_ID2;
			System.out.println("onCreateDialog2  : " + id);
			// set date picker as current date
			return new DatePickerDialog(this, datePickerListener, year, month,
					day);
		
		}
		return null;
	}

	private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

		// when dialog box is closed, below method will be called.
		public void onDateSet(DatePicker view, int selectedYear,
				int selectedMonth, int selectedDay) {
			
			year = selectedYear;
			month = selectedMonth;
			day = selectedDay;

			if(cur == DATE_DIALOG_ID){
				// set selected date into textview
				tvDisplayDate.setText("Date1 : " + new StringBuilder().append(month + 1)
						.append("-").append(day).append("-").append(year)
						.append(" "));
			}
			else{
				tvDisplayDate2.setText("Date2 : " + new StringBuilder().append(month + 1)
						.append("-").append(day).append("-").append(year)
						.append(" "));
			}

		}
	};

}

Time Picker Dialog

Time Picker Dialog

Please leave your valuable comments on this post.