Monday, December 26, 2016

java binary search


import java.util.Arrays;

public class BinarySearch {

   public static void main(String[] args) {

   // initializing unsorted int array
   int intArr[] = {30,20,5,12,55};

   // sorting array
   Arrays.sort(intArr);

   // let us print all the elements available in list
   System.out.println("The sorted int array is:");
   for (int number : intArr) {
   System.out.println("Number = " + number);
   }

   // entering the value to be searched
   int searchVal = 12;

   int retVal = Arrays.binarySearch(intArr,searchVal);
   
   System.out.println("The index of element 12 is : " + retVal);
  
  
  
  
  
  
  
   String[] array = {"hello", "there", "YOU"};

    Arrays.sort(array);

    int index = Arrays.binarySearch(array, "there");

    System.out.print("string search = "+array[index] + "\n");
   
   
   }
}

Friday, November 25, 2016

android abstract class example

public abstract class BaseActivity extends Activity {

    public static final String TAG = "Test";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(myView());
        activityCreated();
    }

    public void printMessage(String message){
        System.out.print(message);
    }


    public abstract int myView();
    public abstract void activityCreated();

}
public class TestActivity extends BaseActivity {

@Override
public int myView() {
     return R.layout.activity_main;
}

@Override
public void printMessage(String message) {
    super.printMessage(message);
}

@Override
public void activityCreated() {
    Log.i("TestActivity", "Created");

    printMessage("Hello Hiren !!!");
  }
}

Thursday, November 24, 2016

Thread Synchronization in Java and Android


public class Main {

public static void main(String[] args) {

SynDemo d = new SynDemo();
Thread1 th1 = new Thread1(d);
Thread2 th2 = new Thread2(d);

th1.start();
th2.start();

}

}

class SynDemo {

// synchronized

synchronized void printNumber(String string) {
for (int i = 0; i < 2000; i++) {
// Log.i("" + string, String.valueOf(i));
System.out.println(string + " = " + String.valueOf(i));
}
}
}

class Thread1 extends Thread {
private SynDemo d;

public Thread1(SynDemo sDemo) {
d = sDemo;
}

@Override
public void run() {
super.run();
d.printNumber("Thread1");
}
}

class Thread2 extends Thread {

private SynDemo d;

public Thread2(SynDemo sDemo) {
d = sDemo;
}

@Override
public void run() {
super.run();
d.printNumber("T2");
}
}

output:

without synchronized
Thread1 = 0
Thread1 = 1
Thread1 = 2

T2 = 0
T2 = 1
T2 = 2
T2 = 3
T2 = 4
T2 = 5
T2 = 6

Thread1 = 3
Thread1 = 4
Thread1 = 5

with synchronized
Thread1 = 0
Thread1 = 1
Thread1 = 2
Thread1 = 3
Thread1 = 4
Thread1 = 5

T2 = 0
T2 = 1
T2 = 2
T2 = 3
T2 = 4
T2 = 5




Wednesday, November 23, 2016

android custom listener or callback or interface

download: http://www.mediafire.com/file/pmk0jckln50sm78/MyListner1.zip


package collapsingtoolbarlikewhatsapp.startingandroid.com.mylistner;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements MyListener {

    TextView tv_msg;

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

        tv_msg =(TextView) findViewById(R.id.tv_msg);

        MyButton mMyButton = new MyButton(this);

    }

    @Override
    public void callback(MyButton view, String result) {

        System.out.println(" MainActivity callback");

        tv_msg.setText("MainActivity callback" + " result="+result);

    }
}


-----------------------------------------------------------------------------------------


package collapsingtoolbarlikewhatsapp.startingandroid.com.mylistner;

public class MyButton {
    MyListener ml;

    // constructor
    MyButton(MyListener ml) {
        this.ml = ml;

        myLogicToIntimateOthere();
    }

    public void myLogicToIntimateOthere() {
        ml.callback(this, "success");
    }
}


-----------------------------------------------------------------------------------------

package collapsingtoolbarlikewhatsapp.startingandroid.com.mylistner;
import android.view.View;

public interface MyListener {
    // you can define any parameter as per your requirement
    public void callback(MyButton view, String result);
}

Saturday, June 11, 2016

google map with marker

download: http://www.mediafire.com/download/745aagbpb3l64cq/GoogleMapsV2.zip

package info.androidhive.googlemapsv2;

import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends Activity {

// Google Map
private GoogleMap googleMap;
double latitude, longitude;

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

try {
// Loading map
initilizeMap();

// Changing map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
// googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);

// Showing / hiding your current location
googleMap.setMyLocationEnabled(true);

// Enable / Disable zooming controls
googleMap.getUiSettings().setZoomControlsEnabled(false);

// Enable / Disable my location button
googleMap.getUiSettings().setMyLocationButtonEnabled(true);

// Enable / Disable Compass icon
googleMap.getUiSettings().setCompassEnabled(true);

// Enable / Disable Rotate gesture
googleMap.getUiSettings().setRotateGesturesEnabled(true);

// Enable / Disable zooming functionality
googleMap.getUiSettings().setZoomGesturesEnabled(true);

// double latitude = 17.385044;
// double longitude = 78.486671;

LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(
LocationManager.PASSIVE_PROVIDER, 0, 0, mlocListener);

// lets place some 10 random markers
// for (int i = 0; i < 10; i++) {
// // random latitude and logitude
// double[] randomLocation = createRandLocation(latitude,
// longitude);
//
// // Adding a marker
// MarkerOptions marker = new MarkerOptions().position(
// new LatLng(randomLocation[0], randomLocation[1]))
// .title("Hello Maps " + i);
//
// Log.e("Random", "> " + randomLocation[0] + ", "
// + randomLocation[1]);
//
// // changing marker color
// if (i == 0)
// marker.icon(BitmapDescriptorFactory
// .defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
// if (i == 1)
// marker.icon(BitmapDescriptorFactory
// .defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
// if (i == 2)
// marker.icon(BitmapDescriptorFactory
// .defaultMarker(BitmapDescriptorFactory.HUE_CYAN));
// if (i == 3)
// marker.icon(BitmapDescriptorFactory
// .defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
// if (i == 4)
// marker.icon(BitmapDescriptorFactory
// .defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
// if (i == 5)
// marker.icon(BitmapDescriptorFactory
// .defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
// if (i == 6)
// marker.icon(BitmapDescriptorFactory
// .defaultMarker(BitmapDescriptorFactory.HUE_RED));
// if (i == 7)
// marker.icon(BitmapDescriptorFactory
// .defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// if (i == 8)
// marker.icon(BitmapDescriptorFactory
// .defaultMarker(BitmapDescriptorFactory.HUE_VIOLET));
// if (i == 9)
// marker.icon(BitmapDescriptorFactory
// .defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
//
// googleMap.addMarker(marker);
//
// // Move the camera to last position with a zoom level
// if (i == 9) {
// CameraPosition cameraPosition = new CameraPosition.Builder()
// .target(new LatLng(randomLocation[0],
// randomLocation[1])).zoom(15).build();
//
// googleMap.animateCamera(CameraUpdateFactory
// .newCameraPosition(cameraPosition));
// }
// }

} catch (Exception e) {
e.printStackTrace();
}

}

@Override
protected void onResume() {
super.onResume();
initilizeMap();
}

/**
* function to load map If map is not created it will create it for you
* */
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();

// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}

/*
* creating random postion around a location for testing purpose only
*/
private double[] createRandLocation(double latitude, double longitude) {

return new double[] { latitude + ((Math.random() - 0.5) / 500),
longitude + ((Math.random() - 0.5) / 500),
150 + ((Math.random() - 0.5) * 10) };
}

/* Class My Location Listener */
public class MyLocationListener implements LocationListener {

@Override
public void onLocationChanged(Location location) {

googleMap.clear();

MarkerOptions mp = new MarkerOptions();

mp.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));

mp.position(new LatLng(location.getLatitude(), location
.getLongitude()));

try {

Geocoder geo = new Geocoder(getApplicationContext(),
Locale.getDefault());
List<Address> addresses = geo.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
if (addresses.isEmpty()) {
// yourtextboxname.setText("Waiting for Location");
mp.title("Waiting for Location");
} else {
if (addresses.size() > 0) {
// yourtextboxname.setText(addresses.get(0).getFeatureName()
// + ", " + addresses.get(0).getLocality() +", " +
// addresses.get(0).getAdminArea() + ", " +
// addresses.get(0).getCountryName());

mp.title(addresses.get(0).getFeatureName() );
}
}
} catch (Exception e) {
// TODO: handle exception
}

googleMap.addMarker(mp);

googleMap
.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location
.getLongitude()), 16));

}

@Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Disabled",
Toast.LENGTH_SHORT).show();
}

@Override
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Enabled",
Toast.LENGTH_SHORT).show();
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}
}

}



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

    <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.MapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

------------------------------------------------


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="info.androidhive.googlemapsv2"
    android:versionCode="1"
    android:versionName="1.0" >

    <permission
        android:name="info.androidhive.googlemapsv2.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-permission android:name="info.androidhive.googlemapsv2.permission.MAPS_RECEIVE" />

    <uses-sdk
        android:minSdkVersion="12"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <!-- Required to show current location -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    

    <!-- Required OpenGL ES 2.0. for Maps V2 -->
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <!-- Requires OpenGL ES version 2 -->
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name="info.androidhive.googlemapsv2.MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppBaseTheme" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- Goolge API Key -->
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyDA3s19HjFy8jXPMPgEB066Zoen5Ofer5o" />
    </application>

</manifest>

Wednesday, April 13, 2016

json array parsing search in log by "clock"

download: http://www.mediafire.com/download/mwcn2dxyj8znsk5/JSONParsingArray.zip

package com.androidhive.jsonparsing;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.os.Bundle;

public class AndroidJSONParsingActivity extends ListActivity {

// url to make request

static String urlSong = "http://api.lyricsnmusic.com/songs?api_key=e6ea07de4c713953d0fdc9ad49b861&q=Coldplay%20Clocks";

// e6ea07de4c713953d0fdc9ad49b861

// JSON Node names


// contacts JSONArray
JSONArray contacts = null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// Hashmap for ListView


String parsedString = "";

try {


parsedString = convertinputStreamToString(urlSong);

} catch (Exception e) {
e.printStackTrace();
}

// String str =
// "[{\"name\":\"name1\",\"url\":\"url1\"},{\"name\":\"name2\",\"url\":\"url2\"}]";

String str = parsedString;

JSONArray jsonarray;
try {
jsonarray = new JSONArray(str);

for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);

String name = obj.getString("title");
// String url = obj.getString("url");

System.out.println("i="+i+" "+name);
// System.out.println(url);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}



}

public static String convertinputStreamToString(String urlSong)
       throws IOException {

URL url = new URL(urlSong);
URLConnection conn = url.openConnection();

HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();

InputStream is = httpConn.getInputStream();


   if (is != null) {
       StringBuilder sb = new StringBuilder();
       String line;

       try {
           BufferedReader r1 = new BufferedReader(new InputStreamReader(
            is, "UTF-8"));
           while ((line = r1.readLine()) != null) {
               sb.append(line).append("\n");
           }
       } finally {
        is.close();
       }
       return sb.toString();
   } else {
       return "";
   }
}

}


manifest
_____________

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidhive.jsonparsing"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".AndroidJSONParsingActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
       
        <!-- Single List Item View -->
        <activity
            android:label="Single Menu Item"
            android:name=".SingleMenuItemActivity" >
        </activity>
    </application>
   
    <uses-permission android:name="android.permission.INTERNET" />

</manifest>