Infinitely Scrolling List

When you use a List or Grid, sometimes common requirement is to dynamically load more data as the user keeps scrolling down making it a potentially infinite scrolling list. This blog will guide you on how to implement this feature in your app.

Infinitely Scrolling List

We will need is our InfiniteScrollListener class that will implement OnScrollListener. Let’s jump right in and see the code for this class.

public abstract class InfiniteScrollListener implements AbsListView.OnScrollListener {
    private int mBufferItemCount = 10;
    private int mCurrentPage = 0;
    private int mItemCount = 0;
    private boolean mIsLoading = true;

    public InfiniteScrollListener(int bufferItemCount) {
        this.mBufferItemCount = bufferItemCount;
    }

    public abstract void loadMore(int page, int totalItemsCount);

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        // Do Nothing
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        if (totalItemCount < mItemCount) {
            this.mItemCount = totalItemCount;
            if (totalItemCount == 0) {
                this.mIsLoading = true;
            }
        }

        if (mIsLoading && (totalItemCount > mItemCount)) {
            mIsLoading = false;
            mItemCount = totalItemCount;
            mCurrentPage++;
        }

        if (!mIsLoading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + mBufferItemCount)) {
            loadMore(mCurrentPage + 1, totalItemCount);
            mIsLoading = true;
        }
    }

}

Then in our onCreate of Activity We must put this:

mGridView.setOnScrollListener(new InfiniteScrollListener(5) {
            @Override
            public void loadMore(int page, int totalItemsCount) {
                mProgressDialog.show();
                // your code
            }
        });

Download code

Video MediaPlayer

We can stream media, including video, to a MediaPlayer object using a surface view.

Video MediaPlayer

For example, you could use the following layout:

<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"
    android:background="#000000"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <SurfaceView
        android:id="@+id/activity_video_surfView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/activity_video_imageButton_play"/>

    <Button
        android:id="@+id/activity_video_imageButton_play"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:background="@android:drawable/ic_media_play" />

</RelativeLayout>

We will refer to the SurfaceView in the implementation of the Activity class.

Now in our Activity class, add the following interfaces:

public class VideoActivity extends Activity implements SurfaceHolder.Callback{

Your IDE should prompt you to add these unimplemented methods:

@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
    // TODO Auto-generated method stub
}

@Override
public void surfaceCreated(SurfaceHolder arg0) {
//setup
}

@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
    // TODO Auto-generated method stub
}

@Override
public void onPrepared(MediaPlayer mp) {
//start playback
}

In surfaceCreated we must add these code line:

try {
	mMediaPlayer = new MediaPlayer();
	mMediaPlayer.setDisplay(mVidHolder);
	mMediaPlayer.setDataSource(Constants.VID_ADDRESS);
	mMediaPlayer.prepare();
	mMediaPlayer.setOnPreparedListener(this);
	mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (Exception e) {
	e.printStackTrace();
}

In surfaceDestroyed we add this:

mMediaPlayer.stop();

Download code

MediaPlayer Audio

There are different ways to control audio. MediaPlayer is good way. We see how to use MediaPlayer for control audio.

Download code

First step is to create file which name is raw in res/
Then in raw we must paste a song in mp3 format.
MediaPlayer Audio

In order to use MediaPlayer , we have to call a static Method create() of this class. This method returns an instance of MediaPlayer class. Its syntax is as follows:

MediaPlayer mMediaPlayer = MediaPlayer.create(this, R.raw.song);

The second parameter is the name of the song that you want to play. You have to make a new folder under your project with name raw and place the music file into it.

Once you have created the Mediaplayer object you can call some methods to start or stop the music. These methods are listed below.

mMediaPlayer.start();
mMediaPlayer.pause();

you can read more about this methods in this link

Now We see simple example, First we need this strings

<string name="app_name">MediaPlayer</string>
    <string name="now_play">Now Playing:</string>
    <string name="inital_time">0 min, 0 sec</string>
    <string name="pausing_sound">Pausing sound</string>
    <string name="playing_sound">Playing sound</string>
    <string name="action_song">Song</string>

In our activity_main.xml we need couple of textViews and imageButtons.

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ImageView
        android:id="@+id/imageView_profile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:src="@drawable/profile" />

    <LinearLayout
        android:id="@+id/linear_layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="14dp"
        android:orientation="horizontal" >

        <ImageButton
            android:id="@+id/imageButton_media_rew"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="rewind"
            android:src="@android:drawable/ic_media_rew" />

        <ImageButton
            android:id="@+id/imageButton_pause"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14dp"
            android:src="@android:drawable/ic_media_pause" />

        <ImageButton
            android:id="@+id/imageButton_play"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14dp"
            android:src="@android:drawable/ic_media_play" />

        <ImageButton
            android:id="@+id/imageButton_media_ff"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="14dp"
            android:onClick="forward"
            android:src="@android:drawable/ic_media_ff" />
    </LinearLayout>

    <SeekBar
        android:id="@+id/seekBar1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/linear_layout"
        android:layout_toLeftOf="@+id/textView2"
        android:layout_toRightOf="@+id/textView1" />

    <TextView
        android:id="@+id/textView_start_min"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/seekBar1"
        android:text="@string/inital_time"
        android:textAppearance="?android:attr/textAppearanceSmall" />

    <TextView
        android:id="@+id/textView_finish_min"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignTop="@+id/seekBar1"
        android:text="@string/inital_time"
        android:textAppearance="?android:attr/textAppearanceSmall" />

    <TextView
        android:id="@+id/textView_title_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/now_play"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView_title_name"
        android:layout_alignBottom="@+id/textView_title_name"
        android:layout_marginLeft="5dp"
        android:layout_toRightOf="@+id/textView_title_name" />

</RelativeLayout>

The last step in MainActivity

package com.thedeveloperworldisyours.mediaplayer;

import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.thedeveloperworldisyours.mediaplayer.utils.Constants;

public class MainActivity extends Activity implements OnClickListener {

	public TextView mSongName, mStartTimeField, mEndTimeField;
	private MediaPlayer mMediaPlayer;
	private double mStartTime = 0;
	private double mFinalTime = 0;
	private Handler mMyHandler = new Handler();;
	private int mForwardTime = 5000;
	private int mBackwardTime = 5000;
	private SeekBar mSeekbar;
	private ImageButton mPlayButton, mPauseButton;
	public static int mOneTimeOnly = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mSongName = (TextView) findViewById(R.id.textView_name);
		mStartTimeField = (TextView) findViewById(R.id.textView_start_min);
		mEndTimeField = (TextView) findViewById(R.id.textView_finish_min);
		mSeekbar = (SeekBar) findViewById(R.id.seekBar1);
		mPlayButton = (ImageButton) findViewById(R.id.imageButton_play);
		mPauseButton = (ImageButton) findViewById(R.id.imageButton_pause);
		mSongName.setText(Constants.NAME_SONG);
		mMediaPlayer = MediaPlayer.create(this, R.raw.song);
		mSeekbar.setClickable(false);
		mPauseButton.setEnabled(false);

		mPlayButton.setOnClickListener(this);
		mPauseButton.setOnClickListener(this);
	}

	public void play(View view) {
		Toast.makeText(getApplicationContext(),
				getString(R.string.playing_sound), Toast.LENGTH_SHORT).show();
		mMediaPlayer.start();
		mFinalTime = mMediaPlayer.getDuration();
		mStartTime = mMediaPlayer.getCurrentPosition();
		if (mOneTimeOnly == 0) {
			mSeekbar.setMax((int) mFinalTime);
			mOneTimeOnly = 1;
		}

		mEndTimeField.setText(String.format(
				"%d min, %d sec",
				TimeUnit.MILLISECONDS.toMinutes((long) mFinalTime),
				TimeUnit.MILLISECONDS.toSeconds((long) mFinalTime)
						- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
								.toMinutes((long) mFinalTime))));
		mStartTimeField.setText(String.format(
				"%d min, %d sec",
				TimeUnit.MILLISECONDS.toMinutes((long) mStartTime),
				TimeUnit.MILLISECONDS.toSeconds((long) mStartTime)
						- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
								.toMinutes((long) mStartTime))));
		mSeekbar.setProgress((int) mStartTime);
		mMyHandler.postDelayed(UpdateSongTime, 100);
		mPauseButton.setEnabled(true);
		mPlayButton.setEnabled(false);
	}

	private Runnable UpdateSongTime = new Runnable() {
		public void run() {
			mStartTime = mMediaPlayer.getCurrentPosition();
			mStartTimeField.setText(String.format(
					"%d min, %d sec",
					TimeUnit.MILLISECONDS.toMinutes((long) mStartTime),
					TimeUnit.MILLISECONDS.toSeconds((long) mStartTime)
							- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
									.toMinutes((long) mStartTime))));
			mSeekbar.setProgress((int) mStartTime);
			mMyHandler.postDelayed(this, 100);
		}
	};

	public void pause(View view) {
		Toast.makeText(getApplicationContext(),
				getString(R.string.pausing_sound), Toast.LENGTH_SHORT).show();

		mMediaPlayer.pause();
		mPauseButton.setEnabled(false);
		mPlayButton.setEnabled(true);
	}

	public void forward(View view) {
		int temp = (int) mStartTime;
		if ((temp + mForwardTime) <= mFinalTime) {
			mStartTime = mStartTime + mForwardTime;
			mMediaPlayer.seekTo((int) mStartTime);
		} else {
			Toast.makeText(getApplicationContext(),
					"Cannot jump forward 5 seconds", Toast.LENGTH_SHORT).show();
		}

	}

	public void rewind(View view) {
		int temp = (int) mStartTime;
		if ((temp - mBackwardTime) > 0) {
			mStartTime = mStartTime - mBackwardTime;
			mMediaPlayer.seekTo((int) mStartTime);
		} else {
			Toast.makeText(getApplicationContext(),
					"Cannot jump backward 5 seconds", Toast.LENGTH_SHORT)
					.show();
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.imageButton_play:
			play(v);
			break;
		case R.id.imageButton_pause:
			pause(v);
			break;
		default:
			break;
		}
	}

}

Download code

TextChangedListener Android

TextWatcher

You can do the addTextChangedListener() method one time.

 TextChangedListener Android

First step

implements TextWatcher

Then you have a error
add unimplemented method


	@Override
	public void afterTextChanged(Editable s) {

	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {

	}

Now you can need declare you editText and to add listener in onCreate()

public class MainActivity extends ActionBarActivity implements OnClickListener,TextWatcher {

	EditText mEditText;
	Button mButtonSave;

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

		mButtonSave = (Button) findViewById(R.id.activity_main_button_save);
		mEditText = (EditText) findViewById(R.id.activity_main_editText1);

		mEditText.setOnClickListener(this);

		mButtonSave.setEnabled(false);
		mEditText.addTextChangedListener(this);
	}

	@Override
	public void afterTextChanged(Editable s) {

	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		if (mEditText.getText().length() == 0) {
			mButtonSave.setEnabled(false);
		}else{
			mButtonSave.setEnabled(true);
		}
	}

}

Donwload code

Make an HTTP request with android

First of all, request a permission to access network, add following to your manifest:

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

http://www.stoimen.com/blog/wp-content/uploads/2011/04/http.jpg

If you want make an HTTP request, We had recommend extending AsyncTask:

class RequestTask extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... uri) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String responseString = null;
        try {
            response = httpclient.execute(new HttpGet(uri[0]));
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                responseString = out.toString();
                out.close();
            } else{
                //Closes the connection.
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } catch (ClientProtocolException e) {
            //TODO Handle problems..
        } catch (IOException e) {
            //TODO Handle problems..
        }
        return responseString;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        //Do anything with response..
    }
}

Now in your Activity you must make call resquest in onCreate:

new RequestTask().execute("http://stackoverflow.com");

Download code