Create global variable in Android Step-By- Step

Standard

In computer programming, a global variable is a variable that is accessible in every scope (unless shadowed). Interaction mechanisms with global variables are called global environment (see also global state) mechanisms. The global environment paradigm is contrasted with the local environment paradigm, where all variables are local with no shared memory.

Step-1  Declare Variable

MyApplication.Java

public class MyApplication extends Application {
    private static String NAME_SPACE = “You Variable”;
     private static String URL = “You Variable”;
    
    
    public String getURL() {
        
        return URL;
    }
    public void setURL(String uRL) {
        
        URL = uRL;
    }
    public String getNAME_SPACE() {
        return NAME_SPACE;
    }
    public void setNAME_SPACE(String nAME_SPACE) {
        NAME_SPACE = nAME_SPACE;
    }   

}

Step – 2 Register Application In AndroidManifest file

 AndroidManifest.xml

<application
        android:name=”.MyApplication”                                   // Add Name of the Application
        android:allowBackup=”true”
       …

/>

Step – 3 Use Variable in Activity

Put code in oncreate method

public class AddReview extends Activity {

 

     private static  String NAME_SPACE;
     private static  String URL;

 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);    
        setContentView(R.layout.addreview);

    MyApplication myapp = (MyApplication) getApplication();   // make Instant
        URL = myapp.getURL();
        NAME_SPACE = myapp.getNAME_SPACE();

}

}

How to make the Google Map V2 in Android?

Standard

Hello Friends,Thank you for reading my post.

If you have developed any app that contains Google Maps v1, It’s time to upgrade it to Google Maps V2 as google maps version 1 deprecated officially on December 3rd, 2012 and it won’t work anymore. This article aims to give knowledge about how to implements newer Google Maps into your applications. If you have already worked with V1, implementing V2 is very easy. Refer Google Maps Docs for any topic that is not covered in this tutorial.

Step 1:

AndroidManifest.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
package=”com.example.googledemo”
android:versionCode=”1″
android:versionName=”1.0″ >

<permission
android:name=”com.example.googledemo.permission.MAPS_RECEIVE”
android:protectionLevel=”signature” />

<uses-permission android:name=”com.example.googledemo.permission.MAPS_RECEIVE” />

<uses-sdk
android:minSdkVersion=”14″
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” />
<application
android:allowBackup=”true”
android:icon=”@drawable/ic_launcher”
android:label=”@string/app_name”
android:theme=”@android:style/Theme.Light.NoTitleBar” >
<activity
android:name=”com.example.googledemo.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>

<meta-data android:name=”com.google.android.gms.version”
android:value=”@integer/google_play_services_version” />

<!– Goolge API Key –>
<meta-data
android:name=”com.google.android.maps.v2.API_KEY”
android:value=”AIzaSyDjhZbo-jxErPkLzG_SFN1J_FwskNXkCgM” />
</application>

</manifest>

Step 2:

activity_main.xml

<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
xmlns:tools=”http://schemas.android.com/tools&#8221;
android:layout_width=”match_parent”
android:layout_height=”match_parent”

tools:context=”.MainActivity” >
<LinearLayout
android:id=”@+id/ll1″
android:layout_width=”match_parent”
android:layout_height=”60sp”
android:orientation=”horizontal”
android:background=”@android:color/holo_blue_light”>

<TextView

android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_gravity=”center_vertical”
android:textColor=”@android:color/white”
android:paddingLeft=”30sp”
android:textSize=”30sp”
android:text=”Google map” />

<Spinner
android:id=”@+id/view”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_gravity=”center_vertical”
android:layout_marginLeft=”30sp”
android:background=”@android:color/white”
android:entries=”@array/View_arrays”
android:padding=”10sp”
android:prompt=”@string/view_promot”
android:textDirection=”anyRtl” />

</LinearLayout>

<fragment
android:id=”@+id/mapchirag”
android:name=”com.google.android.gms.maps.MapFragment”
android:layout_below=”@+id/ll1″
android:layout_marginTop=”10sp”
android:layout_width=”match_parent”
android:layout_height=”match_parent”/>

</RelativeLayout>

Step – 3

MainActivity.Java

package com.example.googledemo;

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.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity implements LocationListener {

protected LocationManager locationmanager;
protected LocationListener locationlistner;
protected Context context;

String lat;
String provider;
protected double latitude,longitude;
protected boolean gps_enabled,network_enabled;
private GoogleMap googleMap;
Spinner view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

view = (Spinner) findViewById(R.id.view);

locationmanager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationmanager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0    , this);

googleMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.mapchirag)).getMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

view.setOnItemSelectedListener(new OnItemSelectedListener() {

@Override
public void onItemSelected(AdapterView<?> parant, View view,
int position, long id) {

switch (position) {
case 0:
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
break;
case 1:
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
break;
case 2:
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case 3:
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
break;
case 4:
googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
break;
default:

googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

break;
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onLocationChanged(Location location) {

googleMap.clear();
MarkerOptions marker = new MarkerOptions();
marker.position(new LatLng(location.getLatitude(), location.getLongitude()));
marker.title(“Current Location…”);
googleMap.addMarker(marker);

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

marker.position(new LatLng(location.getLatitude()+0.001, location.getLongitude()+0.001));
marker.title(“Loaction 1”);
googleMap.addMarker(marker);

marker.position(new LatLng(location.getLatitude()-0.001, location.getLongitude()-0.001));
marker.title(“Loaction 2”);
googleMap.addMarker(marker);

marker.position(new LatLng(location.getLatitude()+0.001, location.getLongitude()-0.001));
marker.title(“Loaction 3”);
googleMap.addMarker(marker);
marker.position(new LatLng(location.getLatitude()-0.001, location.getLongitude()+0.001));
marker.title(“Loaction 4”);
googleMap.addMarker(marker);
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}

strings.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<resources>
<string name=”app_name”>googleDemo</string>
<string name=”action_settings”>Settings</string>
<string name=”hello_world”>Hello world!</string>
<string name=”view_promot”>choose a View</string>
<string-array name=”View_arrays”>
<item >NORMAL</item>
<item >HYBRID</item>
<item >SATELLITE</item>
<item >TERRAIN</item>
<item >NONE</item>
</string-array>
</resources>

Get the Youtube video title By video ID.

Standard

Hello Friends,

In this blog get the title of youtube video by youtube ID.

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

public class GetTitleById {
    
    public String getTitile(String videoId)
    {
        String json;
        String titile=null;
    
        HttpClient Client = new DefaultHttpClient();
    
        try{
        
            HttpGet httpget =     new HttpGet(“http://gdata.youtube.com/feeds/api/videos/”+videoId+”?v=2&alt=jsonc”);                    
            ResponseHandler<String> responseHandler  =     new BasicResponseHandler();        
            json = Client.execute(httpget, responseHandler);
                                    
            JSONObject object  = new JSONObject(json);
                                        
            JSONObject obj = object.getJSONObject(“data”);
                            
            titile = obj.getString(“title”);
            
                    
        } catch (ClientProtocolException e) {
            
            e.printStackTrace();
        } catch (IOException e) {
            
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
                
        return titile;
    }        

}

How to Check Network Connection in Android?

Standard

Hello friends,

This code is check the network connection in android.
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class ConnectionDetector {

private Context context;

public ConnectionDetector(Context context){
this.context = context;
}

public boolean isConnectionToInternet(){

ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

if(conn != null)
{
NetworkInfo[] info = conn.getAllNetworkInfo();
if(info != null)
{
for(int i = 0; i<info.length; i++)
{
if(info[i].getState() ==  NetworkInfo.State.CONNECTED)
{
return true;
}
}
}
}
return false;
}
}
Here your project AndroidManifest.xml Add the permission.

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