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.

Placing Controls in a Widget in Android and Listening to the events from them.

Hello everyone..

I have already shown how to create a simple widget and add it to the home screen in my previous posts. If you have missed these posts please check it here.

How to create a widget in android?

In the next post I showed you how to listen to a widget delete action and delete the widget.

Now in today’s tutorial I am going to show how to place controls like buttons inside the widget and listen to their events and respond to it.

I am proceeding the same as the previous tutorials.

First I will create a new project named “ControlsInWidget” and name the activity “MyActivity.java”.

Now we will create a layout for this main activity. settings.xml

These are the contents of settings.xml

<TableLayout android:id="@+id/TableLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:id="@+id/tv1"
	android:text="CoderzHeaven Widget Settings Activity"
	android:textColor="@android:color/white"
	android:textSize="15dip"
	android:textStyle="bold"
	android:layout_marginTop="5dip"/>
</TableLayout>

This is the MyActivity. java that uses “settings.xml”

package com.coderzheaven.widgetpack;

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

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

Now we will create the class for the widget which is named “MyWidget.java”.
please follow the instructions in the link while creating this class for the widget.

How to create a widget in android?

Now replace the contents inside MyWidget.java with this one.

package com.coderzheaven.widgetpack;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;

public class MyWidget extends AppWidgetProvider {
	
	public static String WIDGET_SETTINGS_ACTION = "SettingsForWidget";
	public static String WIDGET_RECEIVER_ACTION = "WidgetActionReceiver";
	
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds) {
		
		Log.d("DEBUG","onUpdate");
		RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
		Intent configIntent = new Intent(context, MyActivity.class);
		configIntent.setAction(WIDGET_SETTINGS_ACTION);
		Intent active = new Intent(context, MyWidget.class);
		active.setAction(WIDGET_RECEIVER_ACTION);
		active.putExtra("Message", "Message for Button 1");
		PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0);
		PendingIntent configPendingIntent = PendingIntent.getActivity(context, 0, configIntent, 0);
		remoteViews.setOnClickPendingIntent(R.id.button_one, actionPendingIntent);
		remoteViews.setOnClickPendingIntent(R.id.button_two, configPendingIntent);
		appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
	}
	
	@Override
	public void onReceive(Context context, Intent intent) {
		final String action = intent.getAction();
		if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
			final int appWidgetId = intent.getExtras().getInt(
			AppWidgetManager.EXTRA_APPWIDGET_ID,
			AppWidgetManager.INVALID_APPWIDGET_ID);
		if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
			this.onDeleted(context, new int[] { appWidgetId });
			}
		} else {
		// check, if our Action was called
		if (intent.getAction().equals(WIDGET_RECEIVER_ACTION)) {
			String msg = "";
			try {
				msg = intent.getStringExtra("Message");
			} catch (NullPointerException e) {
				Log.e("Error", "No Message");
			}
			PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);
			NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
			Notification noty = new Notification(R.drawable.icon, "Button in the Widget Clicked.",System.currentTimeMillis());
			noty.setLatestEventInfo(context, "Notification from Widget", msg, contentIntent);
			notificationManager.notify(1, noty);
		}
		super.onReceive(context, intent);
		}
	}
}

Here we have two actions “WIDGET_SETTINGS_ACTION” and “WIDGET_RECEIVER_ACTION” which will be set as action for the two buttons inside the widget.

Now here is the main.xml which is the layout for the widget that contains the controls.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="fill_parent"
	android:orientation="horizontal"
	android:background="@drawable/yellow_bkg"
	android:layout_gravity="center"
	android:layout_height="wrap_content">
<Button 
	android:text="Button1" 
	android:id="@+id/button_one"
	android:layout_weight="1"
	android:layout_gravity="center_horizontal|center"
	android:layout_height="fill_parent"
	android:layout_width="fill_parent"/>
<Button 
	android:text="Button2" 
	android:id="@+id/button_two"
	android:layout_weight="1"
	android:layout_gravity="center_horizontal|center"
	android:layout_height="fill_parent"
	android:layout_width="fill_parent"/>
</LinearLayout>

Widget

If you want the time to be updated every second, your have to modify simple_widget.xml
file and set updatePerdiodMillis to 1000.
The android update 1.6 unfortunately does not support any update periode that is less then 30
minutes.

Please go through this tutorial for setting up the xml for the widget.

How to create a widget in android?

Inside the onReceive we are checking this to ensure which button is clicked. You can write anything inside this function – like a http call or something to update the widget.

if (intent.getAction().equals(WIDGET_RECEIVER_ACTION)) {

}

The second button in the widget launches the activity “MyActivity” and the first one send a notification and doesn’t have a user interface.

Widget

Widget

Widget

You can download the complete eclipse java android source code from here.

Please leave your comments on this post and also share it and like it if this post was useful.

How to get Notified when a widget is deleted?

I have already covered a tutorial on how to start with widgets and how to create a simple widget here..

http://www.coderzheaven.com/2012/06/07/create-widget-android/

Today I will show you how to get notified when a widget is deleted.

if you have already gone through my previous post, then there is only a small change in the “MyWidget.java” file.

we have to add the onReceive() method to the class like this.

package com.coderzheaven.pack;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyWidget extends AppWidgetProvider {
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds) {
		
	}
	@Override
	public void onReceive(Context context, Intent intent) {
			final String action = intent.getAction();
			if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
				final int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
																AppWidgetManager.INVALID_APPWIDGET_ID);
				if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
					this.onDeleted(context, new int[] { appWidgetId });
				}
				Toast.makeText(context, "Widget deleted", Toast.LENGTH_LONG).show();
			} else {
				super.onReceive(context, intent);
			}
			
	}
}

onReceive is always called before onUpdate is called. This code snipped checks the called action
and decides wheather to just run the receive method or the delete method.

I have already shown how to add a widget to the home screen, now for deleting simply press and hold the widget and drag to the delete icon on the bottom of the screen.

When you do this the onReceive() method will be called and a toast will appear saying “Widget Deleted”.

Widgets Android

You can download the complete android source code of the above post from here.

Please leave your valuable comments on this post.

Phone storage is getting low problem solved OR How to install apps on the SDCARD by default in your android device?

Often our android phones may get warning that “Phone storage is getting low” because your apps dont have space to be installed on the phone.
I too had this problem. Then I found out the answer, after doing this all apps installed will go to the sdcard.

First you have to enable USB debugging on your Android device
For that Go to

Settings > Applications > Development > USB debugging.

Note : These are only for “Froyo” Devices

Now you need to download and install the Android SDK on your computer from http://developer.android.com/sdk/. Once you’ve downloaded and extracted the package to the folder of your choice, Click and run SDK Setup.exe and click on Available Packages to the left. If you get an error message at this point, enable “Force https://…” in the Settings. From the list of available packages, select “Usb Driver package”, click on the Install Selected button in the bottom right corner and follow the prompts.
Connect your phone to your computer with a USB-cable. Your OS will prompt you to install new drivers. Choose to install them from the android-sdk/usb_driver folder. Do not mount your device; you only need to plug-in the cable.
Next, if you are on windows open the command prompt by opening the run console and typing cmd.

Navigate to the Android-SDK\tools folder.

In the Android-SDK\tools folder, type in

adb devices

and it should detect your connected device.

All you have to do next is entering

adb shell pm setInstallLocation 2.

and , you’re done! Android will now install apps to the SD card by default.

To switch back to storing software on the internal memory, enter

adb shell pm setInstallLocation 0.

See the screenshot.

Install on SDCARD by default in android device.

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

Hello all …….

I have shown many examples on how to download and upload files in android through this site.

These are other methods for downloadign a file in android.

1. How to Download an image in ANDROID programatically?
2. How to download a file to your android device from a remote server with a custom progressbar showing progress?

I have shown four methods to upload an image to a server.
Check these posts to refer this.

1. Uploading audio, video or image files from Android to server
2. How to Upload Multiple files in one request along with other string parameters in android?
3. ANDROID – Upload an image to a server.
4. How to upload an image from Android device to server? – Method 4

This is yet another example on how to do download a file.

So this is the java code that downloads the file.

package com.coderzheaven.pack;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

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

public class DownloadFileDemo extends Activity {
	
	String dwnload_file_path = "http://coderzheaven.com/sample_folder/sample_file.png";
	String dest_file_path = "/sdcard/dwnloaded_file.png";
	Button b1;
	ProgressDialog dialog = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        b1 = (Button)findViewById(R.id.Button01);
        b1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
				dialog = ProgressDialog.show(DownloadFileDemo.this, "", "Downloading file...", true);
				 new Thread(new Runnable() {
			            public void run() {
			            	 downloadFile(dwnload_file_path, dest_file_path);
			            }
			          }).start();				
			}
		});
    }
    
    public void downloadFile(String url, String dest_file_path) {
    	  try {
    		  File dest_file = new File(dest_file_path);
    	      URL u = new URL(url);
    	      URLConnection conn = u.openConnection();
    	      int contentLength = conn.getContentLength();

    	      DataInputStream stream = new DataInputStream(u.openStream());

	          byte[] buffer = new byte[contentLength];
	          stream.readFully(buffer);
	          stream.close();

	          DataOutputStream fos = new DataOutputStream(new FileOutputStream(dest_file));
	          fos.write(buffer);
	          fos.flush();
	          fos.close();
	          hideProgressIndicator();
	          
    	  } catch(FileNotFoundException e) {
    		  hideProgressIndicator();
    	      return; 
    	  } catch (IOException e) {
    		  hideProgressIndicator();
    	      return; 
    	  }
    }
    
    void hideProgressIndicator(){
    	runOnUiThread(new Runnable() {
		    public void run() {
		    	dialog.dismiss();
		    }
		});  
    }
}

This is the xml file that contains the button.

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="File Download Demo from Coderzheaven \n\nFile to download : http://coderzheaven.com/sample_folder/sample_file.png \n\nSaved Path : sdcard/\n"
    />
<Button 
	android:text="Download File" 
	android:id="@+id/Button01" 
	android:layout_width="wrap_content" 
	android:layout_height="wrap_content">
</Button>
</LinearLayout>

Note : Please add these two permissions in the AndroidManifest.xml

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

download file android

download file android

Please leave your comments and also share this post if you like it.

How to create a scrolling ListView in android?

ListView is like a tableView in iPhone or iOS . In this example i will show you how to add a String Array in to the ListView and also make the listView Scrollable.

First the xml file . Here the line

android:scrollbars=”vertical”

will make the scrolling vertically

<?xml version="1.0" encoding="utf-8"?>
<relativeLayout
android:id="@+id/widget32"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
	<listView
			android:id="@+id/listview"
			android:scrollbars="vertical"
			android:layout_width="fill_parent"
			android:layout_height="200dip"
			android:layout_gravity="fill_vertical"
			android:layout_alignParentTop="true"
			>
		</listView>

</relativeLayout>

Now the java file

package com.Ch.Example.pack;

import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class Example extends Activity
{
    /** Called when the activity is first created. */
	ListView list;
	private List<string> List_file;
	public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        List_file =new ArrayList<string>();
        list = (ListView)findViewById(R.id.listview);

        CreateListView();
    }
	private void CreateListView()
	{
		 List_file.add("Coderzheaven");
		 List_file.add("Google");
		 List_file.add("Android");
		 List_file.add("iPhone");
		 List_file.add("Apple");
		 //Create an adapter for the listView and add the ArrayList to the adapter.
		 list.setAdapter(new ArrayAdapter<string>(Example.this, android.R.layout.simple_list_item_1,List_file));
		 list.setOnItemClickListener(new OnItemClickListener()
		   {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
				{
					//args2 is the listViews Selected index
				}
		   });
	}
}

The screen will be like this

Here is a other useful posts related to listviews.

1. ListView with Sections in android.
2. A Simple Layout with two listViews.

How to read a folder in the assets directory and read files from it in android?

File reading is important in android. For the put the files in the assets folder.

We can able to read

  • foldername
  • filename
  • Contents of the file

First we read the name of the folder.

private String folder_array[];
AssetManager mngr_spinner = getAssets();
try
{
         //"air" is the name of the folder...
	folder_array= mngr_spinner.list("air");
}
catch (IOException e1)
{
	e1.printStackTrace();
}

“folder_array” contains all the names of the folder
Then if the path is set to

folder_array= mngr_spinner.list("air/Buttons Events");

Then the list of file name is got.
If you want to read the file content then do the following..

InputStream is;
try
{
	is = getAssets().open(air/Buttons Events/filename);
	int siz = is.available();
	byte[] buffer = new byte[siz];
	is.read(buffer);
        //This text contains the content of the file..
	String text = new String(buffer);
        is.close();
}
catch (Exception e)
{
	 Toast.makeText(CheatSheet.this,"File Not Found Error.Please ensure that file is not deleted.", Toast.LENGTH_SHORT).show();
}

ProgressBar in ANDROID…..

Progress bars are our basic needs when we want to show something for a long time or some progress takes a long time and we want to show it’s progress.
Keeping that in mind ANDROID also has built in progress views.
There are basically two types of progress views in ANDROID.

ProgressDialog.STYLE_SPINNER and ProgressDialog.STYLE_HORIZONTAL

Take a look at this simple example that loads a progressBar on “onCreate”….

public class Example extends Activity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.main);
    	ProgressDialog dialog = ProgressDialog.show(Example.this, "", "Loading...", true);
    }
}

Custom Toasts in ANDROID.

First, just show an image inside a toast:

package com.Ch.Example.pack;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;


public class Example extends Activity {
    /** Called when the activity is first created. */
	public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        showToast();
    }
	private void showToast()
	{
		Toast toast = new Toast(getApplicationContext());
		ImageView view = new ImageView(getApplicationContext());
		view.setImageResource(R.drawable.fish1);
		toast.setView(view);
		toast.show();
	}
}

This method just displays a text toast:

Context context = getApplicationContext();
CharSequence text = "hai i am here";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.TOP|Gravity.LEFT, 50, 50);
toast.show();


And this method displays a Toast that contains both an image and text:

CharSequence text = "hai i am here";
Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG);
View textView = toast.getView();
LinearLayout lay = new LinearLayout(getApplicationContext());
lay.setOrientation(LinearLayout.VERTICAL);
ImageView view = new ImageView(getApplicationContext());
view.setImageResource(R.drawable.fish1);
lay.addView(view);
lay.addView(textView);
toast.setView(lay);
toast.show();