13 Sep

Integrasi AdMob dengan AndEngine

Step 1. Masukkan SDK AdMob ke dalam Project
Copy sdk file to lib folder inside your project, then right-click on the file build path -> add to build path.

Step 2. Edit AndroidManifest.xml

masukkan permissions ke manifest file

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

Add activity to your manifest file

<activity android:name=”com.google.ads.AdActivity”
android:configChanges=”keyboard|keyboardHidden|orientation| screenLayout|uiMode|screenSize|smallestScreenSize”
android:theme=”@android:style/Theme.NoTitleBar.Fullscreen”/>

Step 3. Change project target

New version of admob sdk requires to set target level to 13 or above. It doesn’t mean that your application won’t works on devices with lower api level.

Right-click on your project then properties->android and select Project Build Taget to Android 3.2

Step 4. Add adView to layout.

Remeber to use RelativeLayout!

<?xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:ads=”http://schemas.android.com/apk/lib/com.google.ads”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent” >

<org.anddev.andengine.opengl.view.RenderSurfaceView
android:id=”@+id/xmllayoutRenderSurfaceView”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:layout_centerInParent=”true”
android:gravity=”center” />
<com.google.ads.AdView
android:id=”@+id/adView”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignBottom=”@id/xmllayoutRenderSurfaceView”
ads:adSize=”BANNER”
ads:adUnitId=”<your code>”
ads:loadAdOnCreate=”true” />
</RelativeLayout>

Step 5. Add layout to activity
Your activity needs to extends LayoutBaseActivity

public class Main extends LayoutGameActivity
Override those two methods

@Override
protected int getLayoutID()
{
return R.layout.main;
}

@Override
protected int getRenderSurfaceViewID()
{
return R.id.xmllayoutRenderSurfaceView;
}

13 Sep

Background ListView becomes black when scrolling

When we scroll ListView, the background become black when scrolling.
The solution is we can set on ListView XML:

android:cacheColorHint="#00000000"

Ketika kita melakukan scroll pada listview, akan muncul background warna hitam.
Caranya adalah dengan menambahkan atribute pada list view di definisi XML sbb:
android:cacheColorHint=”#00000000″

Semoga bermanfaat

12 Aug

Android Passing Parameter Antar Activity

Halo, mumpung ada waktu nulis lagi. Saya akan menulis tutorial sederhana tapi bermanfaat.

Kadang kita membuat program yang menggunakan beberapa activity. sebagai contoh kita punya dua activity dengan activity pertama kita berupa List Daftar Negara. Sedangkan Activity kedua adalah tampilan tentang apa yang dipilih pada Actity pertama. Bagaimana Activity kedua mengetahui apa yang dipilih pada activity pertama?

Berikut contoh kode programnya:

Intent myIntent = new Intent(this, ActivtyKedua.class);
myIntent.putExtra("pilihanNegara","Indonesia");
startActivity(myIntent);

Kode program di atas merupakan kode program yang berguna untuk melakukan pemindahan activity disertai dengan passing parameter. Parameter yang dipassing adalah “pilihanNegara” dengan isi “Indonesia”. Bagaimana cara mengambilnya dari Activity kedua?

Intent myIntent= getIntent();
String pilihanNegera = intent.getStringExtra("pilihanNegara")

Kode program di atas merupakan kode program pada Activity kedua, di mana parameter pilihanNegara diambil dari getStringExtra(). Ingat, getStringExtra() digunakan karena tipe datanya adlah String. Kalau integer kita dapat mengambilnya dengan cara getIntExtra().

Semoga jelas dan dapat bermanfaat :)

18 Jun

Camera Picture Taken on Android

public class MakePhotoActivity extends Activity {

	private final static String DEBUG_TAG = "MakePhotoActivity"; 
	private Camera camera; 
	private int cameraId = 0;
        public void onClick(View view) { 
	    camera.takePicture(null, null, 
	    new PhotoHandler(getApplicationContext())); 
        }

        protected void onPause() { 
	    if (camera != null) { 
		camera.release(); 
		camera = null; 
	    } 
	    super.onPause(); 
        }
        private int findFrontFacingCamera() { 
	    int cameraId = -1; 

	    int numberOfCameras = Camera.getNumberOfCameras(); 
            for (int i = 0; i < numberOfCameras; i++) { 	
                CameraInfo info = new CameraInfo(); 	
                Camera.getCameraInfo(i, info); 
		if (info.facing == CameraInfo.CAMERA_FACING_FRONT) { 
			Log.d(DEBUG_TAG, "Camera found"); 
			cameraId = i; break; 
		} 
	} 
	return cameraId; 
}
public class PhotoHandler implements PictureCallback
{ 
	
	private final Context context; 
	public PhotoHandler(Context context) {
		this.context = context; 
	}
        private File getDir() { 
	File sdDir = Environment
		.getExternalStoragePublicDirectory(
		Environment.DIRECTORY_PICTURES); 
	return new File(sdDir, &quot;CameraAPIDemo&quot;); 
}
public void onPictureTaken(
  byte[] data, Camera camera) { 

	File pictureFileDir = getDir(); 
	if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) { 	
              Log.d(Constants.DEBUG_TAG, 
		  "Can't create directory to save image."); 
		Toast.makeText(context, 
		  "Can't create directory to save image.", 
		  Toast.LENGTH_LONG).show(); 
	return; 
} 

18 Jun

Video Recording On Android

public class VideoCapture extends Activity 
	implements OnClickListener, 
	SurfaceHolder.Callback {    
     MediaRecorder recorder;
     SurfaceHolder holder;
     boolean recording = false;

public void surfaceCreated(SurfaceHolder holder) {
	prepareRecorder();
}
public void surfaceChanged(SurfaceHolder holder, 
	int format, int width, int height) {
}
public void surfaceDestroyed(SurfaceHolder holder) {    
        if (recording) {        
                  recorder.stop();        
                  recording = false;    
        }    
        recorder.release();    
        finish();
}
private void prepareRecorder() {  recorder.setPreviewDisplay(holder.getSurface());    try {        recorder.prepare();    } catch (IllegalStateException e) {        e.printStackTrace();        finish();    } catch (IOException e) {        e.printStackTrace();        finish();    }}
public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
  requestWindowFeature(Window.FEATURE_NO_TITLE);
  getWindow().setFlags(
		WindowManager.LayoutParams.FLAG_FULLSCREEN,
 		WindowManager.LayoutParams.FLAG_FULLSCREEN);
	setRequestedOrientation(
		ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);recorder = new MediaRecorder();initRecorder();setContentView(R.layout.main);

	SurfaceView cameraView = 
		(SurfaceView)findViewById(R.id.CameraView);
	holder = cameraView.getHolder();
	holder.addCallback(this);
  holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);cameraView.setClickable(true);cameraView.setOnClickListener(this);
}
private void initRecorder() {
	recorder.setAudioSource(
		MediaRecorder.AudioSource.DEFAULT);
	recorder.setVideoSource(
		MediaRecorder.VideoSource.DEFAULT);
	CamcorderProfile cpHigh = CamcorderProfile
		.get(CamcorderProfile.QUALITY_HIGH);
	recorder.setProfile(cpHigh);
	recorder.setOutputFile("/sdcard/
		videocapture_example.mp4");
	recorder.setMaxDuration(50000); // 50 s
         recorder.setMaxFileSize(5000000); // 5 mb
}
public void onClick(View v) {    
        if (recording) {        
              recorder.stop();        
              recording = false;

	     // selalu panggil init untuk record ulang        
              initRecorder();        
               prepareRecorder();    
        } else {        
             recording = true;        
             recorder.start();    
        }
}

18 Jun

Read Write SD Card on Android

pertama yang harus dilakukan adalah membuka AndroidManifest.xml dan tambahkan Permission berikut:

android.permission.WRITE_EXTERNAL_STORAGE

Cara Menulis Data ke File SD Card

File file = new File("/sdcard/mysdfile.txt");
file.createNewFile();
FileOutputStream fos = 
		new FileOutputStream(file); 

OutputStreamWriter osw = 
		new OutputStreamWriter(fos);
osw.append(txtData.getText());
osw.close();
fos.close();

Cara Membaca Data dari File SD Card

File file = new File("/sdcard/mysdfile.txt");
FileInputStream fis = 
	new FileInputStream(file);
BufferedReader myReader = 
	new BufferedReader(new InputStreamReader(fis)); 
String aDataRow = ""; 
String aBuffer = ""; 
while ((aDataRow = myReader.readLine()) != null) {
	aBuffer += aDataRow + "\n"; 
} 
txtData.setText(aBuffer); 
myReader.close();