Friday, January 31, 2014

Android ListView Tutorial

Berikut adalah activity_main.xml

<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="List View Example" />

    <ListView
        android:id="@+id/lv_example"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </ListView>


</LinearLayout>

Buat Android XML file custom_item.xml

<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="List View Example" />

    <ListView
        android:id="@+id/lv_example"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </ListView>


</LinearLayout>

Buat class Model.java dalam folder src/<nama package Anda>

public class Model {

int id;
String nama;
int image;

public Model() {
}

public Model(int id, String nama, int image) {
super();
this.id = id;
this.nama = nama;
this.image = image;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getNama() {
return nama;
}

public void setNama(String nama) {
this.nama = nama;
}

public int getImage() {
return image;
}

public void setImage(int image) {
this.image = image;
}

}

Buat class Adapter.java dalam folder src/<nama package Anda>

import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class Adapter extends ArrayAdapter<String> {
private Context context;
private int custom_resources;
private String[] ids;
private ArrayList<Model> models;
public Adapter(Context context, int custom_resources, String[] ids, ArrayList<Model> models) {
super(context, custom_resources, ids);
this.context = context;
this.custom_resources = custom_resources;
this.ids = ids;
this.models = models;
}
public View getView(int position, View convertView, ViewGroup group) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(custom_resources, group, false);
ImageView iv_image = (ImageView) convertView.findViewById(R.id.iv_image);
TextView tv_nama = (TextView) convertView.findViewById(R.id.tv_name);
int id = Integer.parseInt(ids[position]);
for (int x = 0; x < models.size(); x++) {
if (id == models.get(x).getId()) {
iv_image.setImageResource(models.get(x).getImage());
tv_nama.setText(models.get(x).getNama());
Model model = new Model(models.get(x).getId(), models.get(x).getNama(), models.get(x).getImage());
tv_nama.setTag(model);
break;
}
}
return convertView;
}

}

Berikut adalah code dalam MainActivity.java

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

public class MainActivity extends Activity {
ListView lv_example;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv_example = (ListView) findViewById(R.id.lv_example);
showList();
lv_example.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> adapter, View view, int selected, long arg3) {
String text = ((Model) view.findViewById(R.id.tv_name).getTag()).getNama();
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void showList() {
ArrayList<Model> models = new ArrayList<Model>();
models.add(new Model(0, "Angky Cahaya Putra", R.drawable.ic_launcher));
models.add(new Model(1, "08968xxxxxxx", R.drawable.ic_launcher));
models.add(new Model(2, "SEAMOLEC Tutorial", R.drawable.ic_launcher));
String[] ids = new String[models.size()];
for (int x = 0; x < models.size(); x++) {
ids[x] = Integer.toString(models.get(x).getId());
}
Adapter adapter = new Adapter(getApplicationContext(), R.layout.custom_item, ids, models);
lv_example.setAdapter(adapter);
}

}

Android Media Player Tutorial

Sebelum memulai tutorial ini, buat folder terlebih dahulu folder raw di dalam folder res. copy lagu (pada contoh kali ini adalah song1.mp3) ke folder raw yang telah dibuat di dalam folder res

Berikut adalah activity_main.xml

<LinearLayout 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:orientation="vertical"
    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" >

    <TextView
        android:id="@+id/tv_status"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="" />

    <SeekBar
        android:id="@+id/sb_status"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <ImageButton
            android:id="@+id/btn_play"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/seek_bar"
android:src="@android:drawable/ic_media_play" />

        <ImageButton
            android:id="@+id/btn_stop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
android:src="@android:drawable/ic_dialog_alert" />

        <ImageButton
            android:id="@+id/btn_pause"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
android:src="@android:drawable/ic_media_pause" />
    </LinearLayout>

</LinearLayout>

Berikut adalah code pada MainActivity.java

import android.app.Activity;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;

public class MainActivity extends Activity {
SeekBar sb_status;
ImageButton btn_previous, btn_play, btn_pause, btn_stop, btn_next;
MediaPlayer mp;
TextView tv_status;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Init();
btn_previous.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View view) {
Thread thread = new Thread(new Previous());
thread.start();
}
});
btn_play.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View view) {
Thread thread = new Thread(new Play());
thread.start();
}
});
btn_pause.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View view) {
Thread thread = new Thread(new Pause());
thread.start();
}
});
btn_stop.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View view) {
Thread thread = new Thread(new Stop());
thread.start();
}
});
btn_next.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View view) {
Thread thread = new Thread(new Next());
thread.start();
}
});
}

public void onDestroy() {
super.onDestroy();
Thread thread = new Thread(new Stop());
thread.start();
}

public void Init() {
sb_status = (SeekBar) findViewById(R.id.sb_status);
btn_play = (ImageButton) findViewById(R.id.btn_play);
btn_pause = (ImageButton) findViewById(R.id.btn_pause);
btn_stop = (ImageButton) findViewById(R.id.btn_stop);
tv_status = (TextView) findViewById(R.id.tv_status);
mp = MediaPlayer.create(getApplicationContext(), R.raw.song1);
sb_status.setMax(mp.getDuration());
tv_status.setText("Waiting...");
}

class Play implements Runnable {

@Override
public void run() {
try {
Thread.sleep(1000);
tv_status.setText("Playing...");
mp.start();
Thread thread = new Thread(new SeekBarUpdate());
thread.start();
} catch (Exception ex) {
}
}

}

class Pause implements Runnable {

@Override
public void run() {
try {
Thread.sleep(1000);
tv_status.setText("Pause...");
mp.pause();
} catch (Exception ex) {
}
}

}

class Stop implements Runnable {

@Override
public void run() {
try {
Thread.sleep(1000);
tv_status.setText("Waiting...");
mp.stop();
mp.prepare();
mp.seekTo(0);
sb_status.setProgress(mp.getCurrentPosition());
} catch (Exception ex) {
}
}

}

class Next implements Runnable {

@Override
public void run() {
try {
Thread.sleep(1000);
if (mp.isPlaying()) {
Thread threadStop = new Thread(new Stop());
threadStop.start();
}
mp.setDataSource(getApplicationContext(), Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.song2));
mp.prepare();
Thread threadPlay = new Thread(new Play());
threadPlay.start();
} catch (Exception ex) {
}
}

}

class Previous implements Runnable {

@Override
public void run() {
try {
Thread.sleep(1000);
Thread threadStop = new Thread(new Stop());
threadStop.start();
mp.setDataSource(getApplicationContext(), Uri.parse("android.resource://" + getApplicationContext().getPackageName() + R.raw.song1));
mp.prepare();
Thread threadPlay = new Thread(new Play());
threadPlay.start();
} catch (Exception ex) {
}
}

}

class SeekBarUpdate implements Runnable {

public SeekBarUpdate() {
}

@Override
public void run() {
try {
while (mp.getCurrentPosition() <= mp.getDuration()) {
sb_status.setProgress(mp.getCurrentPosition());
Thread.sleep(1000);
}
} catch (Exception ex) {
}
}
}
}

Thursday, November 28, 2013

Menara Hanoi

Berikut adalah algoritma membuat menara hanoi tidak menggunkan fungsi rekursif:

class Stack:

package hanoi;

public class Stack {

    private String name;
    private int[] data;
    private int size;
    private int top;

    public Stack() {
    }

    public Stack(String name, int[] data, int size, int top) {
        this.name = name;
        this.data = data;
        this.size = size;
        this.top = top;
    }

    public int[] getData() {
        return data;
    }

    public void setData(int[] data) {
        this.data = data;
    }

    public String getName() {
        return name;
    }

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

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public int getTop() {
        return top;
    }

    public void setTop(int top) {
        this.top = top;
    }

    public void push(int item) {
        if (top == size) {
           
        } else {
            data[top] = item;
            System.out.println("Push " + item + " to " + name);
            top++;
        }
    }

    public void pop() {
        if (top == 0) {
           
        } else {
            System.out.println("Pop " + data[top - 1] + " from " + name);
            top--;
        }
    }

    public int getTopStack() {
        int topStack = 0;
        if (top != 0) {
            topStack = data[top - 1];
        }
        return topStack;
    }
}

class Main

package hanoi;

public class Main {

    static void printData(Stack s) {
        System.out.print(s.getName() + ": ");
        for (int x = 0; x < s.getTop(); x++) {
            System.out.print(s.getData()[x] + " ");
        }
        System.out.println("");
    }

    static void move(Stack from, Stack to) {
        int willMove = from.getTopStack();
        from.pop();
        to.push(willMove);
    }

    static void leftToRight(Stack from, Stack to, Stack temp) {
        System.out.println("");
        while (from.getTop() != 0) {
            if (from.getTopStack() > temp.getTopStack() && temp.getTop() == 1) {
                break;
            } else {
                if (to.getTop() == 0 || to.getTopStack() > from.getTopStack()) {
                    move(from, to);
                } else {
                    move(from, temp);
                    rightToLeft(from, to, temp);
                }
            }
        }
        if (temp.getTop() > 0) {
            move(temp, from);
        }
    }

    static void rightToLeft(Stack from, Stack to, Stack temp) {
        System.out.println("");
        while (to.getTop() != 0) {
            if (to.getTopStack() > temp.getTopStack() && temp.getTop() == 1) {
                break;
            } else {
                if (from.getTop() == 0 || from.getTopStack() > to.getTopStack()) {
                    move(to, from);
                } else {
                    move(to, temp);
                    leftToRight(from, to, temp);
                }
            }
        }
        if (temp.getTop() > 0) {
            move(temp, to);
        }
    }

    static void hanoi(Stack from, Stack to, Stack temp) {
        while (to.getTop() != to.getSize()) {
            leftToRight(from, to, temp);
            if (from.getSize() == 0 && temp.getSize() == 0) {
                break;
            }
            System.out.println("==============================");
            printData(from);
            printData(temp);
            printData(to);
            System.out.println("==============================");
        }
    }

    public static void main(String[] args) {
        int size = 4;
        Stack s1 = new Stack("Tower 1", new int[size], size, 0);
        Stack s2 = new Stack("Tower 2", new int[size], size, 0);
        Stack s3 = new Stack("Tower 3", new int[size], size, 0);
        s1.push(4);
        s1.push(3);
        s1.push(2);
        s1.push(1);
        hanoi(s1, s3, s2);
    }
}

Monday, November 18, 2013

Merge Sort In C

#include <stdio.h>

int n = 7;
int bil[] = {5, 3, 8, 4, 7, 2, 1};

void swap(int first, int second) {
    int tampung = bil[second];
    int i;
    for (i = second - 1; i >= first; i--) {
        bil[i + 1] = bil[i];
    }
    bil[first] = tampung;
}

void mergeSort(int startBawah, int endAtas) {
    if (startBawah >= endAtas) {
        return;
    }
    int middle = (startBawah + endAtas) / 2;
    int endBawah = middle;
    int startAtas = middle + 1;
    mergeSort(startBawah, endBawah);
    mergeSort(startAtas, endAtas);
    while ((startBawah <= endBawah) && (startAtas <= endAtas)) {
        if (bil[startBawah] > bil[startAtas]) {
            swap(startBawah, startAtas);
            startBawah++;
            startAtas++;
            endBawah++;
        } else {
            startBawah++;
        }
    }
}

int main() {
    mergeSort(0, n - 1);
    int x;
    for (x = 0; x < n; x++) {
        printf("%d ", bil[x]);
    }
    return 0;
}


Quick Sort In C

#include <stdio.h>

int n = 7;
int bil[] = {5, 3, 8, 4, 7, 2, 1};

void swap(int first, int second) {
    int tampung = bil[first];
    bil[first] = bil[second];
    bil[second] = tampung;
}

void quickSort(int low, int high) {
    int x = low, y = high;
    int pivot = bil[low + (high - low) / 2];
    while (x <= y) {
        while (bil[x] < pivot) {
            x++;
        }
        while (bil[y] > pivot) {
            y--;
        }
        if (x <= y) {
            swap(x, y);
            x++;
            y--;
        }
    }
    if (low < y) {
        quickSort(low, y);
    }
    if (x < high) {
        quickSort(x, high);
    }
}

int main() {
    quickSort(0, n - 1);
    int x;
    for (x = 0; x < n; x++) {
        printf("%d ", bil[x]);
    }
    return 0;
}

Insertion Sort In C

#include <stdio.h>

int n = 7;
int bil[] = {5, 3, 8, 4, 7, 2, 1};

void swap(int first, int second) {
    int tampung = bil[first];
    bil[first] = bil[second];
    bil[second] = tampung;
}

void insertionSort() {
    int x, y, stop, tampung;
    for (x = 1; x < n; x++) {
        stop = x;
        for (y = (x - 1); y >= 0; y--) {
            if (bil[x] < bil[y]) {
                stop = y;
            }
        }
        tampung = bil[x];
        for (y = x - 1; y >= stop; y--) {
            swap(y, (y + 1));
        }
        bil[stop] = tampung;
    }
}

int main() {
    insertionSort();
    int x;
    for (x = 0; x < n; x++) {
        printf("%d ", bil[x]);
    }
    return 0;
}


Selection Sort In C

#include <stdio.h>

int n = 7;
int bil[] = {5, 3, 8, 4, 7, 2, 1};

void swap(int first, int second) {
    int tampung = bil[first];
    bil[first] = bil[second];
    bil[second] = tampung;
}

void selectionSort() {
    int x, y, min;
    for (x = 0; x < n; x++) {
        min = x;
        for (y = (x + 1); y < n; y++) {
            if (bil[min] > bil[y]) {
                min = y;
            }
        }
        swap(x, min);
    }
}

int main() {
    selectionSort();
    int x;
    for (x = 0; x < n; x++) {
        printf("%d ", bil[x]);
    }
    return 0;
}