Array of cities in JS and show it on a div

In this example, I have a bunch of city names as an array variable in JavaScript. Then I want to make a list of links for all the city names.

Here I do it using jQuery:

<div id="kotas"></div>
<script>
var kotas = [ "Banda Aceh", "Langsa", "Lhokseumawe", "Meulaboh", "Sabang", "Subulussalam", "Denpasar", "Pangkalpinang", "Cilegon", "Serang", "Tangerang Selatan", "Tangerang", "Bengkulu", "Gorontalo", "Kota Administrasi Jakarta Barat", "Kota Administrasi Jakarta Pusat", "Kota Administrasi Jakarta Selatan", "Kota Administrasi Jakarta Timur", "Kota Administrasi Jakarta Utara", "Sungai Penuh", "Jambi", "Bandung", "Bekasi", "Bogor", "Cimahi", "Cirebon", "Depok", "Sukabumi", "Tasikmalaya", "Banjar", "Magelang", "Pekalongan", "Purwokerto", "Salatiga", "Semarang", "Surakarta", "Tegal", "Batu", "Blitar", "Kediri", "Madiun", "Malang", "Mojokerto", "Pasuruan", "Probolinggo", "Surabaya", "Pontianak", "Singkawang", "Banjarbaru", "Banjarmasin", "Palangkaraya", "Balikpapan", "Bontang", "Samarinda", "Tarakan", "Batam", "Tanjungpinang", "Bandar Lampung", "Metro", "Ternate", "Tidore Kepulauan", "Ambon", "Tual", "Bima", "Mataram", "Kupang", "Sorong", "Jayapura", "Dumai", "Pekanbaru", "Makassar", "Palopo", "Parepare", "Palu", "Bau-Bau", "Kendari", "Bitung", "Kotamobagu", "Manado", "Tomohon", "Bukittinggi", "Padang", "Padangpanjang", "Pariaman", "Payakumbuh", "Sawahlunto", "Solok", "Lubuklinggau", "Pagaralam", "Palembang", "Prabumulih", "Binjai", "Medan", "Padang Sidempuan", "Pematangsiantar", "Sibolga", "Tanjungbalai", "Tebingtinggi", "Yogyakarta" ];
kotas.sort();
$("#kotas").html(function(){
	var c = "";
	for(var i = 0; i < kotas.length; i++){
		if(i < kotas.length-1)
			c += "<a href='#'>" + kotas[i] + "</a>, ";
		else
			c += "<a href='#'>" + kotas[i] + "</a>";
	}
	return c;
});
</script>

 

How to check is the device connected to internet or not in Android

With this simple snippet, we can check is the device is connected to internet or not:

private boolean isConnected(){
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

So this “isConnected()” returns true if it’s connected, otherwise it returns false.

Listing image files in a directory and populate a ListView from it in Android

I have a directory in sdcard called “mydir” and there are lot of .png image files with another files. Then I want to list only that .png files and populate a ListView from it.

I do it like this:

String path = "/sdcard/mydir";
File directory = new File(path);
if (!directory.exists()){
	directory.mkdir();
}
File[] files = directory.listFiles();

String[] localfiles = new String[files.length];
for (int i = 0; i < files.length; i++)
{
	localfiles[i] = files[i].getName();
}
ArrayAdapter<String> lbadapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, localfiles);


List<String> localfiles = new ArrayList<String>();
for (int i = 0; i < files.length; i++)
{
	if(files[i].getName().contains(".png"))
		localfiles.add(files[i].getName());
}
ArrayAdapter<String> lbadapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, localfiles);

lblist.setAdapter(lbadapter);

lblist.setOnItemClickListener(new AdapterView.OnItemClickListener() {

	@Override
	public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
		final String itemname = (String) parent.getItemAtPosition(position);
		Toast.makeText(getApplicationContext(), itemname, Toast.LENGTH_LONG).show();
	}

});

 

Simple clickable Android ListView example

Follow this short tutorial to create a ListView in Android.

First let’s create the list view element in our layout file:

<ListView
android:id="@+id/lblistview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

Then in your Java file:

lblist = (ListView)findViewById(R.id.lblistview);

String[] items = new String[3];
items[0] = "First item";
items[1] = "Second item";
items[2] = "Third item";

ArrayAdapter<String> lbadapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, items);

lblist.setAdapter(lbadapter);

lblist.setOnItemClickListener(new AdapterView.OnItemClickListener() {

	@Override
	public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
		final String item = (String) parent.getItemAtPosition(position);
		Toast.makeText(getApplicationContext(),item, Toast.LENGTH_LONG).show();
	}

});

By clicking on each item a toast message will be displayed containing item text.

Listing all files in a directory in Android

Let’s say we have a directory in device’s storage called “mydir” and there are files inside it. By using this snippet we can list all names of that files and folders:

String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/maktabamajaziya";
String downloadedbooks = "";
File directory = new File(path);
File[] files = directory.listFiles();
for (int i = 0; i < files.length; i++)
{
	downloadedbooks += files[i].getName() + "\n";
}

Now downloadedbooks string variable contains all files and folders name.

Requesting permission in run time in Android

If we are making an app for Android greater than SDK 23, we need to request some sensitive permissions (for example, to write file in external storage) in run time.

Here is a snippet to do so:

if (Build.VERSION.SDK_INT >= 23) {
	if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
			== PackageManager.PERMISSION_GRANTED) {
	} else {

		ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
	}
}

 

If a folder (directory) is not existed, create it – Android Java Snippet

With this snippet, we are able to check if a folder existed in device’s storage or not. If not, then we create it.

Here is the snippet:

File directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/afolder");
if (! directory.exists()){
	directory.mkdir();
}

 

Simple PHP read and write to a text file

This code snippet reads a text file that if it is not existed it will create one with some text in it.

Next time this code is executed, if the file existed, PHP echoes the content of the file.

<?php
$settingfile = "settings.txt";
$filelink = fopen($settingfile, "r");
$filecontent = fread($filelink, filesize($settingfile));
echo $filecontent;
fclose($filelink);
$newContents = "Hello world!";
if($filecontent != $newContents){
    $settingfile = "settings.txt";
    $filelink = fopen($settingfile, "w");
    fwrite($filelink, $newContents);
    fclose($filelink);
}
?>

Or this one, the better one:

<?php
$settingfile = "settings.txt";
if(file_exists($settingfile)){
    $filelink = fopen($settingfile, "r");
    $filecontent = fread($filelink, filesize($settingfile));
    echo $filecontent;
    fclose($filelink);
}else{
    $astring = "Hello world!";
    $settingfile = "settings.txt";
    $filelink = fopen($settingfile, "w");
    fwrite($filelink, $astring);
    fclose($filelink);
}
?>

 

Changing the skybox material programmatically in Unity

I’m using this simple script after attaching it to UI Buttons to change my skybox materials. Let’s say we have two skybox materials with two UI Buttons to switch between them.

Here is the script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ChangeSky : MonoBehaviour {

	public Material sky1;
	public Material sky2;

	public void SkyOne(){
		RenderSettings.skybox = sky1;
	}

	public void SkyTwo(){
		RenderSettings.skybox = sky2;
	}
}