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.

Android – JellyBean Features

Jelly Bean

Some new features introduced in Jelly bean are listed below:

Offline voice typing: In contrast with the conventional SIRI assistant, voice dictations in Jelly bean can be done in flight mode or without an internet connection. All the phrasing and voice processing is performed locally, i.e. by the phone processor itself. No server interaction is required in Android 4.1 version. Since no internet connection is required, there are no server processing or server load lags and delays in dictation.

Triple buffering: Android used to lag in the race with iPhone and windows phone in terms of smooth visual display and notifications. Gone are those days with the introduction of V4.1; smooth visual and screen transitions can be experienced by the user even in load conditions. Triple buffer is that technique which provides the essence of smoothness in which three buffers of memory are deployed to process pixels even in load conditions. Two buffers are used as same i.e. front buffer and back buffer. Third tier of buffer activates when the back buffer fails to provide the output on the screen.
This maintains the user experience in load conditions and transitions are presented in a smooth manner.

NFC enabled: Expanded as Near field communication technology, it is the new buzzword for Android 4.1 OS. Along with the bluetooth capability, NFC is another example of machine to machine communication between two devices with a tap.

Google Now: Introduced for Jelly Bean, Google now is a search application which provides the search results automatically. It is like the evolution of the application. It learns about the search suited for a particular instant based on search history, location history and returns the best suited searches. This app is accessed via Google search app.

Jelly Bean

Automatic widget resizing: Unlike conventional widget structure, Android 4.1 has introduced the automatic resizing of widget according to the home screen. Icons size is also changed according to the space.

Advanced notification panel: A notification panel cannot be usual one if its about the new version of Android. This is the reason that Jelly bean is introduced with an advanced notification panel, instead of linking the notification with it’s local app, the details of the notification are shown in the panel directly. For eg. If a person receives a new mail in his Email account, the notification panel itself can be used to read the mail instead of directing the user to his Email account.

Some other features like, predictive keywords in terms of advanced algorithm for predicting text has been introduced. Better search results with voice searching, increased frame rates, high synch between rendering and touch inputs are a few other add-ons provided in this new version. Touch prediction, according to Google, is something of interest which predicts the next touch on the screen.

Which you think is the best – Android or iPhone?

This is a question that has been here since 2007. We know there are many advantages for Android phones and Apple’s iPhone. So what you think, which one is the best.

I will say my personal opinion. And I think Android is the best.

Android vs iPhone

What is your opinion?

Are you an iPhone or ANDROID User?

Why you think one is better than the other from your personal experience?

Do you think Fragmentation is a curse for ANDROID or iPhone?

Paste you opinion here and Let’s see what real phone users are thinking.

How to start with ActionBar in Android?

With Android 3.0 Google eliminated the need of hardware menu button which is replaced by Action Bars.

Here is a quick example on how to use ActionBars.

Action Bar in Android

First create a new project and name it ActionBarExample.

Now create a folder named “menu” in res folder and create a new XML file inside it named “action_bar_menu.xml”.

action_bar_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@+id/menuitem1" android:showAsAction="ifRoom" android:title="Test1"></item>
    <item android:id="@+id/menuitem2" android:showAsAction="ifRoom" android:title="Test2"></item>
</menu>

Now the java code for implementing this ActionBar.

MainActivity.java

package com.example.actionbarexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

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

	  @Override
	  public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.action_bar_menu, menu);
	    return true;
	  }

	  @Override
	  public boolean    onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	    case R.id.menuitem1:
	      Toast.makeText(this, "Test 1 Clicked", Toast.LENGTH_SHORT).show();
	      break;
	    case R.id.menuitem2:
	      Toast.makeText(this, "Test 2 Clicked", Toast.LENGTH_SHORT).show();
	      break;

	    default:
	      break;
	    }

	    return true;
	  }
	} 

As there is enough space in the ActionBar otherwise you may see the Overflow menu or you have to use the Option menu button on your phone.

Please leave your comments om this post.

Uploading and Downloading of files – Popular and Useful posts from CoderzHeaven

Here are the links of my most popular posts on downloading and uploading of files to and from your android device.

uploading and downloading images in android

1. How to download a file from a remote site in android? – Another simple example – Method -3

2. How to download a file to your android device from a remote server with a custom progressbar showing progress?

3. How to upload an image from Android device to server? – Method 4

4. Uploading audio, video or image files from Android to server

5. How to Upload Multiple files in one request along with other string parameters in android?

6. How to Download an image in ANDROID programatically?

7. ANDROID – Upload an image to a server

Please leave your comments if you find these posts useful.

Join the Forum discussion on this post

How to set different layouts for Portrait and Landscape in Android?

This simple example shows how to set different layouts for portrait and Landscape in Android.

If you need a detailed explanation please check this url

http://developer.android.com/guide/practices/screens_support.html

Android Supports these different categories of screens.

1. xlarge screens are at least 960dp x 720dp

2. large screens are at least 640dp x 480dp

3. normal screens are at least 470dp x 320dp

4. small screens are at least 426dp x 320dp

We use configuration qualifier for doing this.

To use a configuration qualifier:

  1. Create a new directory in your project’s res/ directory and name it using the format:<resources_name>-<qualifier>
    • <resources_name> is the standard resource name (such as drawable or layout).
    • <qualifier> is a configuration qualifier from table 1, below, specifying the screen configuration for which these resources are to be used (such as hdpi or xlarge).

    You can use more than one <qualifier> at a time—simply separate each qualifier with a dash.

  2. Save the appropriate configuration-specific resources in this new directory. The resource files must be named exactly the same as the default resource files.

For example, xlarge is a configuration qualifier for extra large screens. When you append this string to a resource directory name (such as layout-xlarge), it indicates to the system that these resources are to be used on devices that have an extra large screen.

Table 1. Configuration qualifiers that allow you to provide special resources for different screen configurations.

Screen characteristic Qualifier Description
Size small Resources for small size screens.
normal Resources for normal size screens. (This is the baseline size.)
large Resources for large size screens.
xlarge Resources for extra large size screens.
Density ldpi Resources for low-density (ldpi) screens (~120dpi).
mdpi Resources for medium-density (mdpi) screens (~160dpi). (This is the baseline density.)
hdpi Resources for high-density (hdpi) screens (~240dpi).
xhdpi Resources for extra high-density (xhdpi) screens (~320dpi).
nodpi Resources for all densities. These are density-independent resources. The system does not scale resources tagged with this qualifier, regardless of the current screen’s density.
tvdpi Resources for screens somewhere between mdpi and hdpi; approximately 213dpi. This is not considered a “primary” density group. It is mostly intended for televisions and most apps shouldn’t need it—providing mdpi and hdpi resources is sufficient for most apps and the system will scale them as appropriate. If you find it necessary to provide tvdpi resources, you should size them at a factor of 1.33*mdpi. For example, a 100px x 100px image for mdpi screens should be 133px x 133px for tvdpi.
Orientation land Resources for screens in the landscape orientation (wide aspect ratio).
port Resources for screens in the portrait orientation (tall aspect ratio).
Aspect ratio long Resources for screens that have a significantly taller or wider aspect ratio (when in portrait or landscape orientation, respectively) than the baseline screen configuration.
notlong Resources for use screens that have an aspect ratio that is similar to the baseline screen configuration.

We will start with an example.

Please take a look at the screenshot which describes the above description.

L-2

The main.xml shown inside each folder may be same or different.
Android will automatically select each layout according to the Device resolution whether it is small, normal or HD.

i.e if the Device is of normal resolution and in the portrait mode then the layout inside “layout-normal” will be selected. When we rotate the same device for landscape then then layout under “layout-normal-land” will be selected.

L-1

L-2

Please leave your valuable comments on this post.

How to make a Button appear like a TextView in Android?

Hello all…..

This is a simple trick where we can make the Button appear like a TextView in Android.

This is done by setting the background of Button to null like this.

b.setBackgroundDrawable(null);

This is the xml that contains the button.

<?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"
    >
<Button  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    android:textColor="#FFF"
    android:id="@+id/but"
    />
</LinearLayout>

How to stream an audio in Android?

This is a simple example to how to stream an audio in android.

Here is the java code for that.

package com.coderzheaven.pack;

import android.app.Activity;
import android.app.ProgressDialog;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class StreamAudioDemo extends Activity implements OnClickListener,
OnPreparedListener, OnErrorListener, OnCompletionListener {

    MediaPlayer mp;
    ProgressDialog pd;
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button bt = (Button)findViewById(R.id.play);
    bt.setOnClickListener(this);
}

   @Override
   public void onPrepared(MediaPlayer mp) {
       Log.i("StreamAudioDemo", "prepare finished");
       pd.setMessage("Playing.....");
       mp.start();
  }

  @Override
  public void onClick(View v) {
       try
        {
    	    pd = new ProgressDialog(this);
    	    pd.setMessage("Buffering.....");
    	    pd.show();
            mp = new MediaPlayer();
            mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mp.setOnPreparedListener(this);
            mp.setOnErrorListener(this);
            mp.setDataSource("http://www.robtowns.com/music/blind_willie.mp3");
            mp.prepareAsync();
            mp.setOnCompletionListener(this);
        }
        catch(Exception e)
        {
            Log.e("StreamAudioDemo", e.getMessage());
        }
  	}

  	@Override
  	public boolean onError(MediaPlayer mp, int what, int extra) {
      pd.dismiss();
      return false;
  	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		pd.dismiss();
		Toast.makeText(getApplicationContext(), "Completed", Toast.LENGTH_LONG).show();		
	}
}

This is the xml that contains the button.

<?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"
    >
<Button  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Stream Audio and Play"
    android:id="@+id/play"
    />
</LinearLayout>

When you run this program you will see a button and on clicking on that button you will see a dialog with message “Buffering…..”. Once the buffering is complete the audio will be start playing.

Stream_1

Stream_2

Stream_3

Please leave your valuable comments on this post.

How to load an image from the assets folder in android?

Here is a simple example showing how to load an image stores in assets folder in android?

package com.coderzheaven.pack;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;

public class LoadImageFromAssetsDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        // Get the AssetManager
        AssetManager manager = getAssets();

        // Read a Bitmap from Assets
        try {
        	InputStream open = manager.open("icon.png");
        	Bitmap bitmap = BitmapFactory.decodeStream(open);
        	// Assign the bitmap to an ImageView in this layout
        	ImageView view = (ImageView) findViewById(R.id.ImageView01);
        	view.setImageBitmap(bitmap);
        } catch (IOException e) {
        	e.printStackTrace();
        } 
    }
}

Done.

How to read a serialized object from a file in the raw folder in android?

In my previous post I showed how to serialize an object and save it in sdcard in a file and retrieve it.

Pull out the file from the sdcard and then create a folder named “raw” inside the “res” folder and copy it.

Serialization pull out file.
This example shows how to retreive it when it is in the res/raw folder.

Here is the code that does this.

 public void readFromResources(){
    	 try
         {
         	InputStream is = getResources().openRawResource(R.raw.save_object);
         	ObjectInputStream ois = new ObjectInputStream(is);
         	Person person = (Person)ois.readObject();
         	Log.v("Person : >> Name : ",person.getName() + ", Address : " + person.getAddress() + ", Number : " + person.getNumber());
         }
         catch(Exception ex)
         {
        	 Log.v("Serialization Error >> ",ex.getMessage());
         	 ex.printStackTrace();
         }
    }

You are done. Go on and run it.
Check the Logcat for the results.

Serialization in Android – A Simple example.

Serializing a class file provides a fast and efficeint way to store information produced by your application!

What is serialization?

Serialization is essentually taking a screenshot of a class file and its contents. For example, lets say you have the following class:


package com.coderzheaven.pack;

import java.io.Serializable;

public class Person implements Serializable //Added implements Serializable
{
	String name="";
	private String number="";
	private String address=""; 
	private static final long serialVersionUID = 46543445; 

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

    public void setAddress(String address)
    {
    	this.address = address;
    }
    
    public String getName()
    {
    	return name;
    }
    	
    public String getNumber()
    {
    	return number;
    }
    	
    public String getAddress()
    {
    	return address;
    }
}

Now we will save this data to a file in the SDCARD.
Make sure to add the write permission in the AndroidManifest.xml file.

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

Now the Activity class which does the saving and retrieving of the object.

package com.coderzheaven.pack;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

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

public class SerializationDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Person person = new Person();
        person.setName("CoderzHeaven");
        person.setAddress("CoderzHeaven India");
        person.setNumber("1234567890"); 
        
        //save the object
        saveObject(person);
        
        // Get the Object
        Person person1 = (Person)loadSerializedObject(new File("/sdcard/save_object.bin")); //get the serialized object from the sdcard and caste it into the Person class.
        System.out.println("Name : " + person1.getName());
    }
    
    public void saveObject(Person p){
    	 try
         {
         	ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("/sdcard/save_object.bin"))); //Select where you wish to save the file...
         	oos.writeObject(p); // write the class as an 'object'
         	oos.flush(); // flush the stream to insure all of the information was written to 'save_object.bin'
         	oos.close();// close the stream
         }
         catch(Exception ex)
         {
         	Log.v("Serialization Save Error : ",ex.getMessage());
         	ex.printStackTrace();
         }
    }
    
    public Object loadSerializedObject(File f)
    {
        try
        {
        	ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
        	Object o = ois.readObject();
        	return o;
        }
        catch(Exception ex)
        {
    	Log.v("Serialization Read Error : ",ex.getMessage());
        	ex.printStackTrace();
        }
        return null;
    }
}

Serialization pull out file.

These are the Rules of Serialization

    Always use variables that can actually be serialized
    Never change the class files source after you serialize a class file from it
    Do not use super large int[] arrays (bug described below)

Now check the Logcat for the output.
Please leave your comments on this example.

Download the sample project of this demo from here.

In the next post we will see how to read a serialized object from the raw folder.

How to remove title from AlertDialog in android?

Hello all..

Today I will show you two simple ways to remove title in an android alertdialog.

Actually you can do this in two methods.

Method 1

That takes a custom layot file, inflates it, gives it some basic text and icon, then creates it.

AlertDialog.Builder builder;
AlertDialog alertDialog;

Context mContext = getApplicationContext();
LayoutInflater inflater = (LayoutInflater)
        mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_dialog,
        (ViewGroup) findViewById(R.id.layout_root));

TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Hello, this is a custom dialog!");
ImageView image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.android);

builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
alertDialog = builder.create();
alertDialog.show()

Method 2

Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

But it doesn’t work when creating an AlertDialog (or using the Builder), because it already disables the title and use a custom one internally.

Also, one can do that with a style, eg in styles.xml:

<style name="FullHeightDialog" parent="android:style/Theme.Dialog">
   <item name="android:windowNoTitle">true</item>
</style>

And then:

Dialog dialog = new Dialog(context, R.style.FullHeightDialog);

How to set line spacing in a textview in android?

This is really simple in android. TextViews has a property called “lineSpacingExtra” which you can change to set the line spacing.

   <TextView 
           android:text="Data" 
		  	android:id="@+id/textview" 
		  	android:layout_gravity="top"
		  	android:gravity="left"
		  	android:layout_width="fill_parent" 
		  	android:layout_height="wrap_content"
		  	android:layout_centerVertical="true"
		  	android:layout_margin="5dp"
		  	android:padding="5dp"
		  	android:textSize="20sp"
		  	android:lineSpacingExtra="10dp">
		  </TextView>

OR

you can call

textView.setLineSpacing()

in the java code itself.

A Simple FlashLight Application.

Here is a simple Application on how to use flashlight in android.

package com.coderzheaven.pack;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class FlashLightActivity extends Activity {

	//flag to detect flash is on or off
	private boolean isLighOn = false;

	private Camera camera;

	private Button button;

	@Override
	protected void onStop() {
		super.onStop();

		if (camera != null) {
			camera.release();
		}
	}

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

		button = (Button) findViewById(R.id.buttonFlashlight);

		Context context = this;
		PackageManager pm = context.getPackageManager();

		// if device support camera?
		if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
			Log.e("err", "Device has no camera!");
			return;
		}
		try{
			camera = Camera.open();
			final Parameters p = camera.getParameters();
	
			button.setOnClickListener(new OnClickListener() {
	
				@Override
				public void onClick(View arg0) {
	
					if (isLighOn) {
	
						Log.i("info", "torch is turn off!");
	
						p.setFlashMode(Parameters.FLASH_MODE_OFF);
						camera.setParameters(p);
						camera.stopPreview();
						isLighOn = false;
	
					} else {
	
						Log.i("info", "torch is turn on!");
	
						p.setFlashMode(Parameters.FLASH_MODE_TORCH);
	
						camera.setParameters(p);
						camera.startPreview();
						isLighOn = true;
	
					}
	
				}
			});
		}catch(Exception e){
			Toast.makeText(this, "Your device doesnot have FlashLight capability", Toast.LENGTH_LONG).show();
		}

	}
}

Now the layout file main.xml.

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

    <Button
        android:id="@+id/buttonFlashlight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
       	android:layout_centerVertical="true"
       	android:layout_centerHorizontal="true"
        android:text="Torch" />

</RelativeLayout>

AndroiManifest.xml file contents.

Make sure to add the permissions.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.coderzheaven.pack"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="5" />

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />

    <application
        android:debuggable="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".FlashLightActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

Download the android java source code from here.

please leave your valuable comments on this post.

How to make a http call repeatedly from a service in android?

We may have applications in which we may have to make repeated calls to a webservice. At that time services may be useful.

This is such an example in which we will be creating a Service in android to create a repeated call to a webservice in a time delay of some seconds or milliseconds.

OK We will start.

First We will create a new android project named “AcessWebFromService” and in the main java file copy this code.

package com.coderzheaven.pack;

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

public class AcessWebFromServiceDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        startService(new Intent(AcessWebFromServiceDemo.this, MyService.class));
    }
}

You may be getting some errors after this. Now we will clear all the errors.

Now create another class and name it “MyService.java“. This is our Service file that extends Android Service.

Paste this code into this file .

package com.coderzheaven.pack;

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

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service{
	
	private static String TAG = MyService.class.getSimpleName();
	private MyThread mythread;
	public boolean isRunning = false;
	
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		Log.d(TAG, "onCreate");		
		mythread  = new MyThread();
	}

	@Override
	public synchronized void onDestroy() {
		super.onDestroy();
		Log.d(TAG, "onDestroy");
		if(!isRunning){
			mythread.interrupt();
			mythread.stop();
		}		
	}

	@Override
	public synchronized void onStart(Intent intent, int startId) {
		super.onStart(intent, startId); 
		Log.d(TAG, "onStart");
		if(!isRunning){
			mythread.start();
			isRunning = true;
		}
	}
	
	public void readWebPage(){
          HttpClient client = new DefaultHttpClient();
          HttpGet request = new HttpGet("http://google.com");
          // Get the response
          ResponseHandler<String> responseHandler = new BasicResponseHandler();
          String response_str = null;
		  try {
			 response_str = client.execute(request, responseHandler);
			 if(!response_str.equalsIgnoreCase("")){
				 Log.d(TAG, "Got Response");
			 }
		  } catch (Exception e) {
			 e.printStackTrace();
		  }
	}
	
	class MyThread extends Thread{
		static final long DELAY = 3000;
		@Override
		public void run(){			
			while(isRunning){
				Log.d(TAG,"Running");
				try {					
					readWebPage();
					Thread.sleep(DELAY);
				} catch (InterruptedException e) {
					isRunning = false;
					e.printStackTrace();
				}
			}
		}
		
	}

}

We have called this service to start running in the main java file using this code.

startService(new Intent(AcessWebFromServiceDemo.this, MyService.class));

Now the important thing is for this service to run we have to declare it in the AndroidManifest file.

This is how the AndroidManifest file looks.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.coderzheaven.pack"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AcessWebFromServiceDemo"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <service android:name=".MyService"></service>

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

OK Now you are done. When you run this application you can see the Log coming every three seconds in the LogCat. PLease make sure that you have internet connection in the Emulator or Device.

This is how the Log looks in the Logcat.

Service

Please leave your valuable comments on this post and also share it by hitting a plus(+1) button.

How to initialize an ArrayList in Android?

ArrayList<String> images_arr = 
		new ArrayList<String>(){		
			private static final long serialVersionUID = -1773393753338094625L;
			{
				add("string1");
				add("string2");	
				add("string3");	
				add("string4");	
			}
	};

Creating a custom Sliding GalleryView with Paging in android

This is a simple example showing A sliding Gallery in android. This example shows a sliding gallery with a paging Control and a changing page text which also indicate the page change.

Create a new project named “SlidingGallery” and copy this code into “SlidingGalleryDemo.java“.
My Activity name is “SlidingGalleryDemo.java” here.

package com.coderzheaven.pack;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class SlidingGalleryDemo extends Activity {
	
	Gallery ga;
	int width, height;
	LinearLayout linear;
	LinearLayout layout;
	Integer[] pics = {
			R.drawable.android_1,
			R.drawable.android_2,
    		R.drawable.android_3,
    		R.drawable.android_4,
    		R.drawable.android_5   
    };
	ImageView paging;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	 super.onCreate(savedInstanceState);
	     setContentView(R.layout.threemenu);
	     
	     layout = (LinearLayout) findViewById(R.id.imageLayout1);
	        
	     DisplayMetrics displaymetrics = new DisplayMetrics();
	     getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
	     width = displaymetrics.heightPixels;
	     height = displaymetrics.widthPixels;
			
	     for(int i=0; i<pics.length; i++)
         {
          	paging = new ImageView(this);
        	paging.setId(i);
        	paging.setBackgroundResource(R.drawable.unsel);
        	layout.addView(paging);
         }
	     
	     ga = (Gallery)findViewById(R.id.thisgallery);
	     ga.setAdapter(new ImageAdapter(this));
	     
	     ga.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) 
				{					
					System.out.println("SELECTED : " + arg2);
				}	        	
	        });
    }

    public class ImageAdapter extends BaseAdapter {

    	private Context ctx;
    	int imageBackground;
    	int pre=-1;
    	public ImageAdapter(Context c) {
			ctx = c;
		}

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

    	public View getView(int arg0, View convertView, ViewGroup arg2) {

		     ImageView iv;
		     LinearLayout layoutnew = new LinearLayout(getApplicationContext());            
		     layoutnew.setOrientation(LinearLayout.VERTICAL);
		        
             if (convertView == null) 
             {
            	iv = new ImageView(ctx);
            	iv.setImageResource(pics[arg0]);
     			iv.setScaleType(ImageView.ScaleType.FIT_XY);
     			int temp =(int) (height/1.7f);
     			int temp_y = (int) ((3*temp)/2.0f);
     			iv.setLayoutParams(new Gallery.LayoutParams(temp,temp_y));
     			iv.setBackgroundResource(imageBackground);
             }
             else
             {
            	iv = (ImageView) convertView;
             }
             TextView tv = new TextView(ctx);
 			 tv.setText("Page " + (arg0+1));
 			 tv.setTextColor(0xFFFFFFFF);
 			 tv.setPadding(0, 15, 0, 0);
 		     tv.setTextSize(18);
 			 tv.setGravity(Gravity.CENTER); 
			 layoutnew.addView(iv);
			 layoutnew.addView(tv);
    		
    		return layoutnew;
    	}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			if(pre !=-1)
    		{
    			ImageView img = (ImageView) findViewById(pre);
    			img.setBackgroundResource(R.drawable.unsel);
    		}
    		ImageView img1 = (ImageView) findViewById(position);
    		img1.setBackgroundResource(R.drawable.sel);
    		this.pre = position;
    		return position;
		}
    }
}

Now create a new class and name it “GalleryCustom.java” which extends “Gallery” and copy this code into it.

package com.coderzheaven.pack;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Gallery;

public class GalleryCustom extends Gallery {

    public GalleryCustom(Context ctx, AttributeSet attrSet) 
    {
        super(ctx,attrSet);
    }

    @SuppressWarnings("unused")
	private boolean isScrollingLeft(MotionEvent e1, MotionEvent e2)
    { 
           return e2.getX() > e1.getX(); 
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY){
      return true;  
    }
}

Now we will create the layout for the page. Copy this code to the main.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="fill_parent"
    android:keepScreenOn="true"  
    android:background="@drawable/Hotpink">
    
    <LinearLayout 
	    android:layout_width="fill_parent"
	    android:id="@+id/imageLayout1"
	    android:layout_marginBottom="5dip"
	    android:layout_alignParentBottom="true"
	    android:gravity="center_horizontal|center_vertical"
	    android:orientation="horizontal"
	    android:layout_height="wrap_content">  
	 </LinearLayout>
	 
	<LinearLayout 
	    android:layout_width="fill_parent"
	    android:id="@+id/imageLayout"
	    android:gravity="center"
	    android:layout_alignParentTop="true"
	    android:layout_above="@+id/imageLayout"
	    android:layout_height="fill_parent" >
    
		<com.coderzheaven.pack.GalleryCustom
		    android:id="@+id/thisgallery"
		    android:spacing="60dip"
		    android:layout_width="fill_parent"
		    android:layout_height="wrap_content" />
		    
    </LinearLayout>
    
</RelativeLayout>

OK Its done. Now run the project and see the result.

Gallery 1

Gallery 1

Gallery 1

Gallery 1

Gallery 1

Please comment and share this post if you like it.

How to delete a contact in android?

Hello all previously I have shown how to list all contacts in your phone and in another post I showed how to programatically create a contact in android.
In today’s tutorial I will show you how to delete a contact in android programatically.

This simple code does that.

 public static boolean deleteContact(Context ctx, String phone, String name) {
        Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
        Cursor cur = ctx.getContentResolver().query(contactUri, null, null, null, null);
        try {
            if (cur.moveToFirst()) {
                do {
                    if (cur.getString(cur.getColumnIndex(PhoneLookup.DISPLAY_NAME)).equalsIgnoreCase(name)) {
                        String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
                        Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
                        ctx.getContentResolver().delete(uri, null, null);
                        return true;
                    }

                } while (cur.moveToNext());
            }

        } catch (Exception e) {
            System.out.println(e.getStackTrace());
        }
        return false;
    }