You are on page 1of 23

1

List

1. Base Adapter on Grid View…………………………………………………....1


2. Array Adapter on list View…………………………………………………………….4
3. MediaPlayer playing audio file………………………………………………………7
4. WebView……………………………………………………………………………………….9
5. TabLayout Example………………………………………………………………………11
6. VedioPlayerExample…………………………………………………………………….17
7. VideoRecorder………………………………………………………………………………18
8. AsyncTasK Example………………………………………………………………………20

App 1

Base Adapter on Grid View

Step 1

XML File activity_main.xml

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


<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>

Step 2

MainActivity.java

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridView=(GridView)findViewById(R.id.grid);
MyAdapter myAdapter=new MyAdapter(MainActivity.this);
gridView.setAdapter(myAdapter);

}
}

Step 3
2

Write class MyAdpter extending BaseAdapter

public class MyAdapter extends BaseAdapter {


Context context;
public MyAdapter(Context context)
{
this.context=context;
}
@Override
public int getCount() {
return imageIds.length;
}

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

@Override
public long getItemId(int i) {
return 0;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ImageView imageView;
if(view==null)
{
imageView=new ImageView(context);
imageView.setLayoutParams(new
GridView.LayoutParams(90,90));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8,8,8,8);
imageView.setImageResource(imageIds[i]);
}else {

imageView =(ImageView) view;


imageView.setImageResource(imageIds[i]);
}

return imageView;
}

private Integer[]
imageIds={R.drawable.lion,R.drawable.elephant,R.drawable.monkey,

R.drawable.dog,R.drawable.tiger,R.drawable.tiger,R.drawable.lion,R.d
rawable.elephant,R.drawable.monkey,

R.drawable.dog,R.drawable.tiger,R.drawable.tiger,R.drawable.lion,R.d
rawable.elephant,R.drawable.monkey,
3

R.drawable.dog,R.drawable.tiger,R.drawable.tiger,R.drawable.lion,R.d
rawable.elephant,R.drawable.monkey,

R.drawable.dog,R.drawable.tiger,R.drawable.tiger,R.drawable.lion,R.d
rawable.elephant,R.drawable.monkey,

R.drawable.dog,R.drawable.tiger,R.drawable.tiger,R.drawable.lion,R.d
rawable.elephant,R.drawable.monkey,

R.drawable.dog,R.drawable.tiger,R.drawable.tiger,R.drawable.lion,R.d
rawable.elephant,R.drawable.monkey,
R.drawable.dog,R.drawable.tiger,R.drawable.tiger};
}

Step 5

Put few animal images named as above in res/drawables folder

Step 6

Run the project

Step 7

Output
4

App 2

Array Adapter on list View

Step 1

XML File activity_main.xml

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


<ListView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listview"
tools:context="com.takeon.adapternew.MainActivity">

</ListView>

Step 2

XML File inner.html

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
android:id="@+id/imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

Step 3

Write MainActivity.java

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView=(ListView)findViewById(R.id.listview);
5

ArrayList<Animals> arr=new ArrayList<>();


arr.add(new Animals(R.drawable.lion,"LION"));
arr.add(new Animals(R.drawable.elephant,"Elephant"));
arr.add(new Animals(R.drawable.monkey,"Monkey"));
arr.add(new Animals(R.drawable.tiger,"tiger"));
arr.add(new Animals(R.drawable.dog,"Dog"));
arr.add(new Animals(R.drawable.cat,"Cat"));
MyCustomAdapter myCustomAdapter=new
MyCustomAdapter(MainActivity.this,R.layout.inner,arr);
listView.setAdapter(myCustomAdapter);

}
}

Step 4

Write Animals.java

public class Animals {

int ids;
String val;

public Animals(int ids,String val)


{
this.ids=ids;
this.val=val;

public int getIds()


{
return ids;
}
public String getVal()
{

return val;
}
}

Step 5

Write Customized Adapter

public class MyCustomAdapter extends ArrayAdapter {

ArrayList<Animals> arrayList;
public MyCustomAdapter(@NonNull Context context, @LayoutRes int
resource, ArrayList<Animals> objects) {
super(context, resource,objects);
this.arrayList=objects;

}
6

@NonNull
@Override
public View getView(int position, @Nullable View convertView,
@NonNull ViewGroup parent) {
//return super.getView(position, convertView, parent);
View v=convertView;
LayoutInflater inflater= (LayoutInflater)
getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v= inflater.inflate(R.layout.inner,null);
ImageView im=(ImageView)v.findViewById(R.id.imageview);
TextView tx=(TextView)v.findViewById(R.id.txt);

im.setBackgroundResource(arrayList.get(position).getIds());
tx.setText(arrayList.get(position).getVal());
return v;

}
}
Step 6

Save some draw able images of animals named like above to res/drawables folder

Step 7

Run

Step 8 Output
7

App 3

MediaPlayer playing audio file

Step 1

Activity_main.xml

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.takeon.itaudioplayer.MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ITMediaPlayer"
android:layout_gravity="center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/play"
android:layout_gravity="center"
android:text="Play"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/pause"
android:layout_gravity="center"
android:text="Pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/stop"
android:layout_gravity="center"
android:text="Stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</LinearLayout>

Step 2

MainActivity.java

public class MainActivity extends AppCompatActivity {


8

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

Button play=(Button)findViewById(R.id.play);
Button pause=(Button)findViewById(R.id.pause);
Button stop=(Button)findViewById(R.id.stop);

Context context=getApplicationContext();
final MediaPlayer mediaPlayer=MediaPlayer.create(context,
Settings.System.DEFAULT_RINGTONE_URI);

play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mediaPlayer.start();
}
});
pause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mediaPlayer.pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mediaPlayer.stop();
}
});

}
}

Step 3

Run
9

App 4

WebView Example

Step 1

Write activity_main.xml

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:orientation="vertical"
android:layout_height="fill_parent"
tools:context="com.takeon.testwebview.MainActivity">
<WebView
android:layout_width="match_parent"
android:id="@+id/webview"
android:layout_height="match_parent">

</WebView>

</LinearLayout>

Step 2

Get internet permission in AndroidManifest.xml

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

Step 3

Write Main Activity

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView wv=(WebView)findViewById(R.id.webview);
wv.setWebViewClient(new MyClient());
WebSettings ws=wv.getSettings();
ws.setJavaScriptEnabled(true);
ws.setLoadsImagesAutomatically(true);
wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv.loadUrl("file:///android_asset/index.php");
}

private class MyClient extends WebViewClient{


@Override
10

public boolean shouldOverrideUrlLoading(WebView view,


WebResourceRequest request) {
view.loadUrl("file:///android_asset/index.php");
return true;
}

}
}

Step 4

Go to File->new ->Folder->Asset Folder(create asset folder)

And put index.php file there

Step 5

Run

Output
11

App 5

TabLayout Example

Step 1

Add compile 'com.android.support:design:26.0.0-alpha1' to build.gradle and sync the project to add


material design to the project

Step 2

Write activity_main.xml

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context="com.takeon.www.tablayoutexample.MainActivity"

android:orientation="vertical">

<android.support.v7.widget.Toolbar

android:id="@+id/tool"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:background="?attr/colorPrimary"

android:minHeight="?attr/actionBarSize"

android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"

app:popupTheme="@style/ThemeOverlay.AppCompat.Light"

>

</android.support.v7.widget.Toolbar>

<android.support.design.widget.TabLayout

android:id="@+id/tablayout"
12

android:layout_height="wrap_content"

android:layout_width="match_parent"

android:background="?attr/colorPrimary"

android:minHeight="?attr/actionBarSize"

android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

<android.support.v4.view.ViewPager

android:id="@+id/pager"

android:layout_width="match_parent"

android:layout_height="fill_parent">

</android.support.v4.view.ViewPager>

</LinearLayout>

Step 3

Write tab1.xml,tab2.xml and tab3.xml

(tab1.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#f00"
android:layout_height="match_parent">
<TextView
android:text="Tab 1"
android:layout_gravity="center"

android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

(tab2.xml)

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#0f0"
android:layout_height="match_parent">
<TextView
android:text="Tab 1"
13

android:layout_gravity="center"

android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

(tab3.xml)

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#00f"
android:layout_height="match_parent">
<TextView
android:text="Tab 3"
android:layout_gravity="center"

android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

Step 5

Write Main Activity


public class MainActivity extends AppCompatActivity implements
TabLayout.OnTabSelectedListener{
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar=(Toolbar)findViewById(R.id.tool);
tabLayout=(TabLayout)findViewById(R.id.tablayout);
viewPager=(ViewPager)findViewById(R.id.pager);

setSupportActionBar(toolbar);
toolbar.setSubtitle("welcome");
// tabLayout.setTabTextColors(Color.BLUE,Color.RED);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
14

tabLayout.addTab(tabLayout.newTab());
tabLayout.addTab(tabLayout.newTab());
tabLayout.addTab(tabLayout.newTab());

Pager adapter = new Pager(getSupportFragmentManager(), tabLayout.getTabCount());


//Adding adapter to pager
viewPager.setAdapter(adapter);

//Adding onTabSelectedListener to swipe views


tabLayout.setupWithViewPager(viewPager);//setOnTabSelectedListener(this);
tabLayout.getTabAt(0).setText("Tab 1");
tabLayout.getTabAt(1).setText("Tab 2");

tabLayout.getTabAt(2).setText("Tab 3");
tabLayout.getTabAt(2).setIcon(R.drawable.next);

@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(TabLayout.Tab tab) {

@Override
public void onTabReselected(TabLayout.Tab tab) {

}
}

Step 6
Write Pager.java

public class Pager extends FragmentStatePagerAdapter{


int count;
public Pager(FragmentManager fm,int count)
{
15

super(fm);
this.count=count;
}
@Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
Tab1 tab1=new Tab1();
return tab1;
case 1:
Tab2 tab2=new Tab2();
return tab2;
case 2:
Tab3 tab3=new Tab3();
return tab3;
default:
return null;
}
}

@Override
public int getCount() {
return this.count;
}
}

Step 7

Write Tab1.java, Tab2.java and Tab3.java

public class Tab1 extends Fragment {


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {

return inflater.inflate(R.layout.tab1,container,false);

// return super.onCreateView(inflater, container, savedInstanceState);


}
}
public class Tab2 extends Fragment {
@Nullable
@Override
16

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,


@Nullable Bundle savedInstanceState) {

return inflater.inflate(R.layout.tab2,container,false);

// return super.onCreateView(inflater, container, savedInstanceState);


}
}

public class Tab3 extends Fragment {


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {

return inflater.inflate(R.layout.tab3,container,false);

// return super.onCreateView(inflater, container, savedInstanceState);


}
}
Step 8

Run

Output
17

App 6
VideoPlayer example

Step 1
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.takeon.myvedioplayer.MainActivity">

<VideoView
android:id="@+id/videoView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>

Step 2
MainActivity.java

package com.takeon.myvedioplayer;
public class MainActivity extends AppCompatActivity {
VideoView videoView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoView=(VideoView)findViewById(R.id.videoView);
videoView.setVideoPath(
"http://www.______.com/movies/movie.mp4");

MediaController mediaController = new


MediaController(this);
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);

videoView.setOnPreparedListener(new
MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
Log.i("Duration", "Duration = " +
18

videoView.getDuration());
}
});

videoView.start();
}
}

Step 3
Run

App 7
Video Recorder
Write activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.takeon.myvideorecorder.MainActivity">

<Button
android:id="@+id/record"
android:text="Record Video"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</android.support.constraint.ConstraintLayout>

Step 2
Write MainActivity.java

public class MainActivity extends AppCompatActivity {


private static final int VIDEO_CAPTURE = 102;
private Uri fileUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button record=(Button)findViewById(R.id.record);
if (!hasCamera())
record.setEnabled(false);
record.setOnClickListener(new View.OnClickListener() {
19

@Override
public void onClick(View view) {
startRecording();
}
});

private boolean hasCamera() {


if (getPackageManager().hasSystemFeature(

PackageManager.FEATURE_CAMERA_ANY)){
return true;
} else {
return false;
}
}

protected void
onActivityResult(int requestCode,
int resultCode, Intent data) {
if (requestCode == VIDEO_CAPTURE) {
if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Video recording cancelled.",
Toast.LENGTH_LONG).show();
}
else if (resultCode==RESULT_OK) {
Toast.makeText(this, "Video has been saved to:\n" + fileUri,
Toast.LENGTH_LONG).show();
}

else {
Toast.makeText(this, "Failed to record video",
Toast.LENGTH_LONG).show();
}
}
}
public void startRecording()
{
File mediaFile = new

File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/myvideo.mp4");
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = Uri.fromFile(mediaFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
20

startActivityForResult(intent, VIDEO_CAPTURE);
}

}
Step 3
Run

Output

App 8
AsyncTask HttpUrlConnection Example

Write permission for Internet in AndroidManifest.xml

Step 1

package com.takeon.myasynctask;
21

public class MainActivity extends AppCompatActivity {


TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=(TextView)findViewById(R.id.tx);
OpenPage openPage=new OpenPage();
openPage.execute();

final class OpenPage extends AsyncTask<String, Integer, Boolean>


{

private HttpURLConnection connection;


private URL url;
boolean b=false;

protected void onPreExecute() {


try {
url = new URL("https://www.google.com/");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
connection = (HttpURLConnection)url.openConnection();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}

@Override
protected Boolean doInBackground(String... strings) {
Boolean ok=null;
try {
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK ) {

b=true;
}
22

else if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND ) {


// textView.setText("La page n'existe pas");
b=false;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return b;
}

@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if (b)
{
textView.setText("this page exists");
}
else {
textView.setText("this page not exists");
}
}
}

Step 2

Write activity_main.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.takeon.myasynctask.MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/tx"
/>
23

</LinearLayout>

Output

You might also like