Archive for 2018
//tanpa controller
VideoView simpleVideoView = (VideoView) findViewById(R.id.vd); // initiate a video view
simpleVideoView.setVideoURI(Uri.parse("android.resource://" + this.getPackageName() + "/" + R.raw.v));
simpleVideoView.start();
[Droid] VideoView tanpa Controller
Use the permission Internet
MainActivity.java
import android.os.Bundle;
import android.app.*;
import com.google.android.gms.ads.AdRequest; //Import class AdRequest
import com.google.android.gms.ads.AdView; //import class Adview
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}
}
Main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView android:text="@string/app_name" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<!--menambahkan elemen AdView untuk menampilkan iklan/ads-->
<com.google.android.gms.ads.AdView
android:id="@+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
ads:adSize="BANNER"
ads:adUnitId="@string/banner_ad_unit_id">
</com.google.android.gms.ads.AdView>
</RelativeLayout>
String.xml
<string name="banner_ad_unit_id">ca-app-pub-3940256099942544/6300978111</string>
[DROID] Admob Banner
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body bgcolor="white">
<h1>Melki Mitsuki</h1><br>
<div id="tambah">tambah
</div>
<div id="remove">remove
</div>
<script>
$(document).ready(function(){
$('#tambah').click(function(){
$('#tambah').append('<div>tambah element berada di dalam dan di bagian bawah ganti append dengan prepend (untuk element berada di atas) after (eleement berada di bagian bawah tapi di luar) before (element berada di atas tapi diluar) remove (untuk menghapus elemen menurut id) empty (menghapus isi dari sebuah element menurut id)</div>');
});
$('#remove').click(function(){
$('#tambah').remove();
});
});
</script>
</body>
</html>
[JQUERY] menulis dan menghapus element
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body bgcolor="white">
<h1>Melki Mitsuki</h1><br>
<form>
<input type="text" id="t"/>
<input type="submit" value="klik"/>
</form>
<script>
$(document).ready(function(){
$('form').submit(function(){
var isi=($('#t').val());
$('h1').text(isi);
event.preventDefault();
});
});
</script>
</body>
</html>
[JQUERY] Get & Set
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h1>Melki Mitsuki</h1><br>
<div id="div1">gunakan # untuk idi</div>
<div class="div2">gunakan titik untuk class</div>
<div class="div3">ini div3</div>
<div class="div3">ini div3</div>
<div class="div3">ini div3</div>
<div class="div3">ini div3</div>
<script>
$('h1').click(function(){
$('h1').css('color','red');
});
$('#div1').click(function(){
$('#div1').css('color','green');
});
$('.div2').click(function(){
$('.div2').css('color','yellow');
});
$('.div3').click(function(){
$(this).css('color','red');
});
</script>
<h3> kalian dapat mengganti event click dengan mouseenter dan mouseleave</h3>
</body>
</html>
[JQUERY] event
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h1>Melki Mitsuki</h1><br>
<div id="div1">gunakan # untuk idi</div>
<div class="div2">gunakan titik untuk class</div>
<script>
$(document).ready(function(){
$('h1').css('color','red');
$('#div1').css('color','blue');
$('.div2').css('color','green');
});
</script>
</body>
</html>
[JQUERY] selection
https://www.petanikode.com/html-canvas/
Langkah Awal select canvas
<!DOCTYPE html>
<html>
<head>
<meta charset goyang dombret="utf-8">
<title>Tutorial HTML 5 Canvas</title>
</head>
<body>
<canvas id="myCanvas" width="640" height="480" style="border:1px solid #000000;">
</canvas>
<script type="text/javascript"> var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); </script>
</body> </html>
Code Code Menggambar pada Canvas
1. ctx.fillRect(x,y,1,1);
menggambar titik 1px
2. ctx.beginPath()
untuk memulai/ membuat garis baru.
3. ctx.moveTo(x,y)
untuk menentukan titik awal
4. ctx.lineTo(x,y)
untuk menentukan titik akhir
5. ctx.stroke()
untuk menggambar garisnya.
6. ctx.strokeRect(x,y,w,h)
persegi dengan garis (outline) saja.
7. ctx.fillRect(x,y,w,h)
persegi dengan polesan warna (default-nya hitam).
8. ctx.clearRect(x,y,w,h)
persegi transparan untuk menghapus.
Seperti biasa, kita harus memberikan titik koordinat x dan y. Sementara nilai w dan h untuk lebar dan tingginya.
9. ctx.closePath()
untuk menggambar garis dari titik terakhir ke titik awal secara otomatis.
10. strokeText("text",x,y)
untuk teks dengan garis luar (outline) saja.
11. fillText("text",x,y)
untuk teks dengan warna (default hitam).
12. ctx.font = "64px Arial";
Jenis dan ukuran font
13. drawImage(img, x, y);
Menambahkan gambar
14. var image= new Image();
image.src="./bird.png";
ctx.drawImage(image,10,10,200,200);
Menambahkan image ke canvas
[WEB] Canvas dan javascript
AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
MainActivity.java
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.*;
import android.widget.*;
public class MainActivity extends Activity {
Button button;
ProgressDialog progressdialog;
public static final int Progress_Dialog_Progress = 0;
String ImageURL ;
URL url;
URLConnection urlconnection ;
int FileSize;
InputStream inputstream;
OutputStream outputstream;
byte dataArray[] = new byte[1024];
long totalSize = 0;
EditText txt, edit;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edit = (EditText)findViewById(R.id.edit);
button = (Button)findViewById(R.id.lihat);
txt =(EditText)findViewById(R.id.text);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ImageURL= edit.getText().toString();
new ImageDownloadWithProgressDialog().execute(ImageURL);
}});}
public class ImageDownloadWithProgressDialog extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(Progress_Dialog_Progress);}
@Override
protected String doInBackground(String... aurl) {
int count;
try {
url = new URL(aurl[0]);
urlconnection = url.openConnection();
urlconnection.connect();
FileSize = urlconnection.getContentLength();
inputstream = new BufferedInputStream(url.openStream());
outputstream = new FileOutputStream("/sdcard/downloadurl.txt");
while ((count = inputstream.read(dataArray)) != -1) {
totalSize += count;
publishProgress(""+(int)((totalSize*100)/FileSize));
outputstream.write(dataArray, 0, count);}
outputstream.flush();
outputstream.close();
inputstream.close();
} catch (Exception e) {}
return null;}
protected void onProgressUpdate(String... progress) {
progressdialog.setProgress(Integer.parseInt(progress[0]));}
@Override
protected void onPostExecute(String unused) {
dismissDialog(Progress_Dialog_Progress);
try {
FileReader fr = new FileReader("/sdcard/downloadurl.txt");
BufferedReader br = new BufferedReader(fr);
String text;
while ((text = br.readLine()) != null)
txt.setText(text);}
catch (FileNotFoundException fnfe) {
fnfe.getMessage();}
catch (IOException ioe) {
ioe.getMessage();}
Toast.makeText(MainActivity.this, "Text Downloaded Successfully", Toast.LENGTH_LONG).show();
}} protected Dialog onCreateDialog(int id) {
switch (id) { case Progress_Dialog_Progress:
progressdialog = new ProgressDialog(MainActivity.this);
progressdialog.setMessage("Downloading Text From Server...");
progressdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressdialog.setCancelable(false);
progressdialog.show();
return progressdialog;
default:
return null;}}}
[DROID] Baca Tulis Isi File Via Diwnload File With AsyncTask
public void simpan_data(){
SavePreferences("PrefDemo","save");
}
private void SavePreferences(String key, String value) {
SharedPreferences sharedPreferences = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit(); }
public void lihat_data(){
showPreferences("PrefDemo");
}
private void showPreferences(String key){
SharedPreferences sharedPreferences =
this.getPreferences(Context.MODE_PRIVATE);
String Data = sharedPreferences.getString(key, "");
TexView.setText(Data);
}
[DROID] SavedPreverences
AndroidManifest.xml
MainActivity.java
import android.content.Intent;
import android.app.*;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
// nama kelas harus sama dengan nama file nya
public class MainActivity extends Activity {
Button bKirim;
RadioGroup radio;
EditText tNama;
EditText tHobi;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
inisialisasi();
bKirim.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), second.class);
i.putExtra("variabelnama", tNama.getText().toString());
i.putExtra("variabelumur", tHobi.getText().toString());
int id = radio.getCheckedRadioButtonId();
RadioButton radiobutton = (RadioButton)findViewById(id);
i.putExtra("variabelkelamin", radiobutton.getText().toString());
startActivity(i);
}
});
}
private void inisialisasi() {
bKirim = (Button)findViewById(R.id.kirim);
radio = (RadioGroup)findViewById(R.id.jeniskelamin);
tNama = (EditText)findViewById(R.id.nama);
tHobi= (EditText)findViewById(R.id.hobi);
}
}
second.java
import android.content.Intent;
import android.app.*;
import android.os.Bundle;
import android.widget.TextView;
public class second extends Activity {
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondmain);
Intent i = getIntent();
String nerimanama = i.getStringExtra("variabelnama");
String nerimaumur = i.getStringExtra("variabelumur");
String kelamin = i.getStringExtra("variabelkelamin");
TextView nama = (TextView)findViewById(R.id.namaValue);
TextView umur = (TextView)findViewById(R.id.hobivalue);
TextView jk = (TextView)findViewById(R.id.jeniskelaminvalue);
nama.setText(nerimanama);
umur.setText(nerimaumur);
jk.setText(kelamin);
}
}
[DROID] Parsing Data Antar Activity
Cara Import Library (firebase)
1. bikin project baru kemudian edit file build.gradle pertama dan tambahkan classpath untuk firebase
sperti ini
classpath 'com.google.gms:google-services:3.2.0' // google-services plugin
kemudian tambahkan maven dibawah jcenter() sperti ini
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com" // Google's Maven repository
}
}
}
2. setelah itu edit file build.gradle yang kedua (module)
tambahkan compile untuk firebase didalam dependencies
dan letakan aplly plugin di paling bawah
apply plugin: 'com.google.gms.google-services'
3. terahir tambahkan library firebase.jar kedalam folder libs
buat folder baru (libs) di dalam folder yang ada folder src dan java
4.klik dan tahan file firebase.jar nya lalu klik add to projek nanti otomatis akan muncul dialog untuk mendowload maven library
selesai
nb: jika download maven library tidak muncul bisa library di dependencies dan di firebase.jar tidak sama versinya
Kedua
coba tutup IDENYA atau pindah projek kemudian buka kembali projek yang tadi nanti akan muncul maven download library
[DROID] Import Library (firebase)
AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
MainActivity.java
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.*;
public class MainActivity extends Activity {
Button button;
ProgressDialog progressdialog;
public static final int Progress_Dialog_Progress = 0;
String ImageURL = "https://www.android-examples.com/wp-content/uploads/2016/04/demo_download_image.jpg" ;
URL url;
URLConnection urlconnection ;
int FileSize;
InputStream inputstream;
OutputStream outputstream;
byte dataArray[] = new byte[1024];
long totalSize = 0;
ImageView imageview;
String GetPath ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button)findViewById(R.id.button);
imageview = (ImageView)findViewById(R.id.image);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new ImageDownloadWithProgressDialog().execute(ImageURL);
}
});
}
public class ImageDownloadWithProgressDialog extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(Progress_Dialog_Progress);
}
@Override
protected String doInBackground(String... aurl) {
int count;
try {
url = new URL(aurl[0]);
urlconnection = url.openConnection();
urlconnection.connect();
FileSize = urlconnection.getContentLength();
inputstream = new BufferedInputStream(url.openStream());
outputstream = new FileOutputStream("/sdcard/demo_photo1.jpg");
while ((count = inputstream.read(dataArray)) != -1) {
totalSize += count;
publishProgress(""+(int)((totalSize*100)/FileSize));
outputstream.write(dataArray, 0, count);
}
outputstream.flush();
outputstream.close();
inputstream.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
progressdialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused) {
dismissDialog(Progress_Dialog_Progress);
GetPath = Environment.getExternalStorageDirectory().toString() + "/demo_photo1.jpg";
imageview.setImageDrawable(Drawable.createFromPath(GetPath));
Toast.makeText(MainActivity.this, "Image Downloaded Successfully", Toast.LENGTH_LONG).show();
}
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case Progress_Dialog_Progress:
progressdialog = new ProgressDialog(MainActivity.this);
progressdialog.setMessage("Downloading Image From Server...");
progressdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressdialog.setCancelable(false);
progressdialog.show();
return progressdialog;
default:
return null;
}
}
}
[DROID] AsyncTask Download Image
MainActivity.java
import android.app.*;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
public class MainActivity extends Activity {
GridView grid;
int[] imageId = {
R.drawable.fb1,
R.drawable.item, };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
CustomGrid adapter = new CustomGrid(this,imageId);
grid = (GridView) findViewById(R.id.grid);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You select ",
Toast.LENGTH_SHORT).show();
}
});
}
}
CustomGrid.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomGrid extends BaseAdapter {
private Context mContext;
private final int[] Imageid;
public CustomGrid(Context c, int[] Imageid) {
mContext = c;
this.Imageid = Imageid;
}
@Override
public int getCount() {
return Imageid.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.grid_single, null);
ImageView imageView = (ImageView) grid.findViewById(R.id.grid_image);
imageView.setImageResource(Imageid[position]);
} else {
grid = (View) convertView;
}
return grid;
}
}
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<GridView
android:id="@+id/grid"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="15dp"
android:columnWidth="100dp"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="columnWidth" />
</LinearLayout>
grid_single.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp">
<ImageView
android:id="@+id/grid_image"
android:layout_width="100dp"
android:layout_height="150dp"/>
</LinearLayout>
[DROID] Grid view image
https://www.google.com/amp/s/rekayuu.wordpress.com/2014/11/03/tugas-kuliahmembuat-alarm-sederhana-untuk-android/amp/
[DROID] alarm sederhana
package com.mycompany.myapp;
import android.app.*;
import android.content.*;
import android.os.*;
import android.widget.*;
public class MainActivity extends Activity {
@Override
private TextView batteryTxt;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context ctxt, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
batteryTxt.setText(String.valueOf(level) + "%");
if(level==89){batteryTxt.setText("okokokok");}}};
@Override
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.main);
batteryTxt = (TextView) this.findViewById(R.id.l);
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));}}
[DROID] cek level battery
package com.mycompany.myapp;
import java.io.IOException;
import android.os.Bundle;
import android.app.ActionBar;
import android.app.Activity;
import android.app.WallpaperManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from activity_main.xml
setContentView(R.layout.main);
// Create an actionbar
ActionBar actionBar = getActionBar();
actionBar.show();
// Locate ImageView in activity_main.xml
ImageView mywallpaper = (ImageView) findViewById(R.id.wallpaper);
// Attach image into ImageView
mywallpaper.setImageResource(R.drawable.mery);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Create an actionbar menu
menu.add("Set as Wallpaper")
// Add a new Menu Button
.setOnMenuItemClickListener(this.SetWallpaperClickListener)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
return super.onCreateOptionsMenu(menu);
}
// Capture actionbar menu item click
OnMenuItemClickListener SetWallpaperClickListener = new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// Retrieve a WallpaperManager
WallpaperManager myWallpaperManager = WallpaperManager
.getInstance(MainActivity.this);
try {
// Change the current system wallpaper
myWallpaperManager.setResource(R.drawable.mery);
// Show a toast message on successful change
Toast.makeText(MainActivity.this,
"Wallpaper successfully changed", Toast.LENGTH_SHORT)
.show();
} catch (IOException e) {
// TODO Auto-generated catch block
}
return false;
}
};
}
AndroidManifest.xml
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.SET_WALLPAPER" >
</uses-permission>
Main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/wallpaper"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
[DROID] Set Walpaper
/*langkah pertama kita buat form dulu dengan html dalam file php*/
<html>
<form method="post" action="">
<input type="text" name="nama" placeholder="nama"/>
<input type="text" name="umur" placeholder="umur"/>
<input type="submit" name="tombol" value="insert"/>
</form>
/*kemudian buat koneksi kedatabase*/
<?php $con=mysqli_connect("localhost","root","","nama_database");
/*setelah itu ambil nama input dari form yg sudah kita buat*/
if(isset($_POST['tombol'])){
$nama=$_POST['nama'];
$umur=$_POST['umur'];
/*nah langkah yang ini untuk mengirim data kedalam database*/
$masukan="INSERT INTO nama_tabel (nama_kolom1,nama_kolom2) value('$nama','$umur')";
$query=mysqli_query($con,$masukan);
/*buat logika*/
if($query){
echo" data berhasil dimasukan";
}else{ echo" gagal memasukan data";
}}
?>
/*jangan lupa penutup html */
</html>
/* jika ada yang error mungkin ada tanda kutip yang hilang silahkan di tanyakan di komentar apa yang error:) /*
[WEB] cara menyimpan data(text) kedalam database mysql
MainActivity.java
package com.mycompany.myapp;
import android.app.*;
import android.content.*;
import android.os.*;
import android.widget.*;
import android.net.*;
public class MainActivity extends Activity{
EditText tx;
String text;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tx=(EditText)findViewById(R.id.tx);
Intent receivedIntent = getIntent();
String receivedAction = receivedIntent.getAction();
String receivedType = receivedIntent.getType();
if(receivedAction.equals(Intent.ACTION_SEND)){
if(receivedType.startsWith("text/")){
String receivedText = receivedIntent.getStringExtra(Intent.EXTRA_TEXT);
if(receivedText != null) {
tx.setText(receivedText);
}}} finish();}}
main.xml
buat EditText dengan id tx
AndroidManifest.xml
tambahkan intent filter
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mycompany.myapp" >
<uses-permission
android:name="android.permission.READ_SMS"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/*" />
</intent-filter>
</activity>
</application>
</manifest>
[DROID] ambil data yg di bagikan aplikasi lain
function auto($url){
$cx = curl_init();
curl_setopt($cx, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($cx, CURLOPT_URL, $url);
$ch = curl_exec($cx);
curl_close($cx);
return $ch;
}
[WEB] function untuk menjalankan url tanpa membuka url
Menampilkan json tanpa Array
final TextView t=(TextView)findViewById(R.id.txt);
Button b=(Button)findViewById(R.id.btn);
b.setOnClickListener(new Button.OnClickListener(){@Override
public void onClick(View p1)
{String jsonString = "{\"pelatih\":{\"nama\":\"adi saka\",\"kota\":\"Langit\",\"murid\":[{\"nama\":\"sila gading\",\"umur\":6},{\"nama\":\"putri tunggal\",\"umur\":8},{\"nama\":\"anka satu\",\"umur\":7}]}}";
try {
JSONObject object = new JSONObject(jsonString);
JSONObject objData = object.getJSONObject("pelatih");
for(int i = 0; i < objData.length(); i++){
t.setText(objData.getString("nama")+" "+objData.getString("kota"));}
} catch (JSONException e) {
e.printStackTrace();}
}
});
[DROID] (json) menampilkan json ke textView
cara memgambil data json dan menampilkannya dengan php
1.bikin file data.json untuk menyimpan data data json dengan ini contoh sperti ini
{"nama":"melki","umur","18"}
2.bikin file php dengan script sperti ini
<?php
//mengambil data di data.json
$file=file_get_contents("data.json");
$ambil= json_decode($file, true);
//menampilkan data
echo $ambil["nama"]."<br>";
echo $ambil["umur"];
?>
Perbedaan json_decode dan json_encode
json_decode untuk data json
json_encode untuk mengkonversi array
[WEB] (JSON) mengambil dan menampilkan data json
<?php
/*cara menampilkan isi database mysqli*/
/*pertam kita lakukan koneksi seperti di bawah ini*/
<?php
$db_host = 'localhost';
$db_user = 'username';
$db_pass = 'password';
$db_name = 'nama_database';
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
/*lakukan logika*/
if (!$conn) { die ('Gagal terhubung MySQL: ' . mysqli_connect_error()); }
/*kemudian kita ambil data yang ada didalam mysqli sperti ini*/
$sql = 'SELECT* FROM nama_tabel ';
$query = mysqli_query($conn, $sql);
/*lakukan logika*/
if (!$query) { die ('SQL Error: ' . mysqli_error($conn)); }
/*terahir kita tampilkan data yang sudah di ambil tadi sperti ini*/
while ($row = mysqli_fetch_array($query)){
$a=$row['nama_kolom'];
echo $a;
}
?>
[WEB] menampilkan isi database dengan php mysqli
<?php
$zip = new ApkArchive;
$file = $zip->open("tes.zip");
if ($file === TRUE) {
$zip->extractTo("hasil-unzip");
$zip->close(); // tutup
echo "Berhasil!";
}
else
{
echo "Gagal";
}
?>
[WEB] Extrack Zip
Buat folder terlebih dahulu didalam public_html sebagai penyimpanan file
Untuk menyimpan file jenis lain kita tinggal mengganti extensi file di script php dibawah
Index.html
<!DOCTYPE html>
<html>
<body>
<form action="proses.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="UploadFile" id="UploadFile">
<input type="submit" value="Upload Gambar" name="submit">
</form>
</body>
</html>
proses.php
<?php
$var = "video/";
$folder =$var.basename($_FILES["UploadFile"]["name"]);
$FileType = pathinfo($folder,PATHINFO_EXTENSION);
if ($_FILES["UploadFile"]["size"] >9999999999999999){
echo "Maaf, ukuran file terlalu besar.";}
if($FileType != "mp4" &&
$FileType != "mkv" &&
$FileType != "3gp" &&
$FileType != "avi"){
echo "extensi file tidak di dukung";}else{ move_uploaded_file($_FILES["UploadFile"]["tmp_name"], $folder);}?>
[WEB] upload file to server
Nb:
untuk bisa berpindah anda harus mengetahui nama package aplikasi target dan activitynya
Seperti contoh di bawah
com.melki adalah package
Dan MainActivity adalah Activitynya
Tapi disini activitynya ditulis package + activity =com.melki.MainActivity
import android.app.*;
import android.os.*;
import android.widget.*;
import android.view.*;
import android.content.*;
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn=(Button)findViewById(R.id.btn);
btn.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v){
Intent ii=new Intent();
ii.setComponent(new ComponentName("com.melki","com.melki.MainActivity"));
try{
startActivity(ii);
}catch(Exception e)
{
Toast.makeText(MainActivity.this,"aplikasi tidak terinstal",Toast.LENGTH_SHORT).show();}};});}}
[DROID] Berpindah Aplikasi (implicit)
import android.app.*;
import android.os.*;
import android.widget.*;
import android.view.*;
import android.content.*;
import android.net.*;
public class MainActivity extends Activity implements View.OnClickListener {
EditText edit;
Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button= (Button) findViewById(R.id.btn);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"whatsappsharing",Toast.LENGTH_SHORT).show();
Intent whatsappintent=new Intent();
whatsappintent.setAction(Intent.ACTION_SEND);
whatsappintent.setType("text/plain");
whatsappintent.putExtra(Intent.EXTRA_TEXT, "testing programing");
whatsappintent.setPackage("com.whatsapp");
startActivity(whatsappintent);
}}
[DROID] Mengirim text Ke Whatsapp (implicit Intent)
Nn: jika iklan tidak tampil maka ganti nama package menggunakan apk editor
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/t"
android:text="wait"/>
</LinearLayout>
MainActivity.java
package com.mycompany.myapp;
import android.app.*;
import android.os.*;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.AdListener;
import android.util.*;
import android.widget.*;
public class MainActivity extends Activity
{
private InterstitialAd mInterstitialAd;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-8053190329240173/4842633610");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {}
@Override
public void onAdFailedToLoad(int errorCode) {}
@Override
public void onAdOpened() {}
@Override
public void onAdLeftApplication() {}
@Override
public void onAdClosed() {
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}});if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();}else{}}
@Override
public void onStart() {
super.onStart();
if(mInterstitialAd.isLoaded()) {
mInterstitialAd.show();}else{}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mycompany.myapp"
android:versionCode="2"
android:versionName="1.2">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<meta-data android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
android:theme="@android:style/Theme.Translucent" />
</application>
</manifest>
Build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "21.1.0"
defaultConfig {
applicationId "com.mycompany.myapp"
minSdkVersion 14
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile 'com.google.android.gms:play-services-ads:+'
compile 'com.google.android.gms:play-services-ads:+'
compile fileTree(dir: 'libs', include: ['*.jar'])
}
Dikutip dari : http://www.sketchwarehelp.com/2017/09/how-to-integrate-admob-interstitial-ads.html?m=1
[DROID] Admob
TextView text=(TextView)findViewById(R.id.txt);
(Buton listener)
String anu="";
for(int a=1; a<10; a++){anu=anu+"text \n";}
u.setText(anu);
[DROID] perulangan for() tampil di TextView
Buatlah sebuah TextView Untuk Menampilkan Hasil Perulangan
import android. os . Bundle ;
import android. app.*;
import android. widget . TextView ;
import java . util . Timer;
import java . util . TimerTask ;
public class MainActivity extends
Activity {
private TextView tv_count ;
int angka = 0;
@Override
protected void onCreate (Bundle savedInstanceState)
{
super . onCreate(savedInstanceState );
setContentView (R . layout.main );
tv_count = (TextView ) findViewById( R . id. tex );
new Timer(). scheduleAtFixedRate ( new TimerTask ()
{
@Override
public void run () {
runOnUiThread (new Runnable() {
@Override
public void run () {
tv_count . setText ("Perulangan ke: " + angka++ );
}});}
// untuk mengatur kecepatan perulangan
}, 1000 , 1000 ); }}
[DROID] perulangan tiap detik berganti
MainActivity.java
import android.content.Intent;
import android.app.*;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button enableButton,disableButton;
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.main); enableButton=(Button)findViewById(R.id.button1); disableButton=(Button)findViewById(R.id.button2); enableButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
startService(new Intent(MainActivity.this,
MyService.class));
}
}); disableButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
stopService(new Intent(MainActivity.this, MyService.class));
}
});
}
}
MyService.java
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
import android.media.*;
public class MyService extends Service {
MediaPlayer n;
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
n= MediaPlayer.create(this,R.raw.owl);
Toast.makeText(this, "The new Service was Created",
Toast.LENGTH_LONG).show();
}
@Override
public void onStart(Intent intent, int startId) {
// For time consuming an long tasks you can launch a new thread here...
n.start();
Toast.makeText(this, " Service Started", Toast.LENGTH_LONG).show();
}
@Override
public void onDestroy() {
n.stop();
Toast.makeText(this, "Service Destroyed",
Toast.LENGTH_LONG).show();
}
}
main.xml
<LinearLayout
xmlns:android=
"http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_margin="5dp"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:textColor="#ffffff"
android:text="Stop Service" />
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_margin="5dp"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:textColor="#ffffff"
android:text="Start Service" />
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mycompany.myapp3" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="MyService"
android:label="Service"/>
</application>
</manifest>
[DROID] Service
MainActicity.java
import android.app.*;
import android.os.*;
import android.net.*;
import android.widget.*;
import android.content.*;
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ConnectivityManager cm = (ConnectivityManager) getApplication().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
Toast.makeText(getApplication(), "You are connected to "+netInfo.getTypeName()+" "+netInfo.getSubtypeName(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplication(), "You don't have connection.", Toast.LENGTH_SHORT).show();
}
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
[DROID] Tes Koneksi Internet
Dialog Native
Ingin suatu halaman aplikasi muncul tapi dengan model dialog ?
Dan bisa muncul dimana saja alias muncul diluar aplikasi
Anda hanya perlu menambahkan code ini
android:launchMode="singleInstance" android:excludeFromRecents="true"android:theme="@android:style/Theme.Dialog"
Kedalam AndroidManifest.xml <activity>
Dan untuk mengatur ukuran dialog anda hanya perlu memberi ukuran yang tadinya wrap_content menjadi 500dip (contoh)
[DROID] Dialog Diluar Aplikasi
<html>
<button type="button" id="autoKlik" onclick="alert('Auto Klik Aktif setiap 50 detik')">Submit</button>
<script>
var button=document.getElementById("autoKlik");
setInterval(function(){
button.click();
}, 50000);
</script>
</html>
[WEB] membuat tombol klik otomatis setiap detik
Untuk mematikan fungsi tombol kembali anda hanya perlu menambahkan coding ini
@Override
public void onBackPressed() {
//jika ingin terjadi sesuatu ketika tombol back di klik maka buatlah fungsi di sini
}
Dan Untuk membuat Tombol Exit Gunakan Coding ini di dalam Fungsi Button
moveTaskToBack(true);
[DROID] Disable back button and create exit button
import android.app.*;
import android.os.*;
import android.widget.*;
import android.content.*;
import android.view.*;
import android.view.View.*;
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);}
//seting button di xml gunakan onClick dan panggil dengan public void
//startclick adalah nilai dari onClick yang ada di Button
public void startclick ( View v){
//ketika tombol di klik maka waktu akan menghitung mundur dari 5000 (5detik) sampai 1000 (1detik)
new CountDownTimer( 5000 ,1000 ){
@Override
//jika waktu telah habis maka halaman akan berpindah
public void onFinish() {
Intent go=new Intent(hal2.this,MainActivity.class);
startActivity(go);
}
@Override
//untuk menampilkan notifikasi waktu yang sedang berhitung mundur ke dialog
public void onTick( long berhenti) {
final Dialog dialog = new Dialog(hal2.this);
dialog.setTitle("Loding"+berhenti/1000);
dialog.show();
}
}. start();
}
}
[DROID] CountDown tombol berwaktu
Perbandingan String
cara menggunakan perbandingan di string yaitu menggunakan equals()
sperti beriku:
String a,b;
a="nilai pertama";
b="nilai kedua";
if(a.equals(b)){lakukan sesuatu}
keterangan : a.equals(b) artinya a==b
[DROID] Perbandingan String (equals)
Sekarang saya akan bagikan script untuk mengScan daftar wifi yang aktif
1.MainActivity.java
package com.melki.droid;
import java.util.List;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView mainText;
WifiManager mainWifi;
WifiReceiver receiverWifi;
List<ScanResult> wifiList;
StringBuilder sb = new StringBuilder();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mainText = (TextView) findViewById(R.id.lihat);
// Initiate wifi service manager
mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
// Check for wifi is disabled
if (mainWifi.isWifiEnabled() == false)
{
// If wifi disabled then enable it
Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled",
Toast.LENGTH_LONG).show();
mainWifi.setWifiEnabled(true);
}
// wifi scaned value broadcast receiver
receiverWifi = new WifiReceiver();
// Register broadcast receiver
// Broacast receiver will automatically call when number of wifi connections changed
registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
mainWifi.startScan();
mainText.setText("Starting Scan...");
}
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, "Refresh");
return super.onCreateOptionsMenu(menu);
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
mainWifi.startScan();
mainText.setText("Starting Scan");
return super.onMenuItemSelected(featureId, item);
}
protected void onPause() {
unregisterReceiver(receiverWifi);
super.onPause();
}
protected void onResume() {
registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
super.onResume();
}
// Broadcast receiver class called its receive method
// when number of wifi connections changed
class WifiReceiver extends BroadcastReceiver {
// This method call when number of wifi connections changed
public void onReceive(Context c, Intent intent) {
sb = new StringBuilder();
wifiList = mainWifi.getScanResults();
sb.append("\n Number Of Wifi connections :"+wifiList.size()+"\n\n");
for(int i = 0; i < wifiList.size(); i++){
sb.append(new Integer(i+1).toString() + ". ");
sb.append((wifiList.get(i)).toString());
sb.append("\n\n");
}
mainText.setText(sb);
}
}}
2.main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<TextView
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_width="wrap_content"
android:id="@+id/lihat"/>
</ScrollView>
3.AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mycompany.myapp" >
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>