Friday, 10 April 2015

Android AsyncTask

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask's generic types


The three types used by an asynchronous task are the following:
  1. Params, the type of the parameters sent to the task upon execution.(Which we passing into  doInBackground(Object[])
  2. Progress, the type of the progress units published during the background computation.
  3. Result, the type of the result of the background computation.


package com.example.mysmpleappforasync;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.util.Log;

public class MyAsync extends AsyncTask<String, Void, Object>{

@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}

@Override
protected void onPostExecute(Object result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.e("onCancelled obj", "onCancelled"+result);

}

@Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}

@SuppressLint("NewApi") @Override
protected void onCancelled(Object result) {
// TODO Auto-generated method stub
super.onCancelled(result);
Log.e("onCancelled obj", "onCancelled"+result);
}

@Override
protected void onCancelled() {
// TODO Auto-generated method stub
super.onCancelled();
Log.e("onCancelled", "onCancelled");

}

@Override
protected Object doInBackground(String... params) {
// TODO Auto-generated method stub
HttpClient hc=new DefaultHttpClient();
HttpPost request=new HttpPost("http://www.mena-properties.com/mena_app/mobilemanager/getRows");
String json="";
JSONObject jobj=new JSONObject();
try {
jobj.accumulate("param","photos");
jobj.accumulate("start", 0);
jobj.accumulate("noofrows", 10);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
json=jobj.toString();
try {
StringEntity se=new StringEntity(json);
request.setEntity(se);
request.setHeader("Accept", "json/application");
request.setHeader("Content-type", "json/application");
try {
HttpResponse res=hc.execute(request);
String jsonResponse = EntityUtils.toString(res.getEntity());
           JSONObject jsobj=new JSONObject(jsonResponse);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

}

Sunday, 7 December 2014

Json Parsing in android


Here I am trying to implement jsonParsing in a Simple way using AsynTask


package com.technomobs.backdoing;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.io.UnsupportedEncodingException;
import java.net.UnknownHostException;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.technomobs.Interfacez.NewsLoadingCompleteInterface;
import com.technomobs.Interfacez.PhotoLoadingCompleteInterface;
import com.technomobs.Interfacez.VideoLoadingComplateInterface;
import com.technomobs.Models.HomePageModel;
import com.technomobs.Utils.Constantz;
import com.technomobs.menaproperties.R;

public class TestimonilLoading extends AsyncTask<String, Void, Object> {
ProgressDialog dialog;
ArrayList<HomePageModel> ArrhomePageModel;
ArrayList<HomePageModel> ArrhomePageModelsnd;
ArrayList<HomePageModel> ArrhomePageModelFinal;

private String errorMessage=null;
private Context context;
JSONArray jsonArraydata; String result;
JSONArray jsonArrayres;
VideoLoadingComplateInterface callback;
HomePageModel homePageModel;
JSONObject jsobj;
JSONObject jsonObject ;
boolean needloading;
public TestimonilLoading(Context context, VideoLoadingComplateInterface promo) {
this.callback=promo;
this.context=context;

Log.e("inside","gallery");
// TODO Auto-generated constructor stub
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
this.dialog=ProgressDialog.show(context, "", "");
this.dialog.setContentView(R.layout.custom_progressbarlayout);
// this.dialog.setMessage("Please wait..");
    this.dialog.show();
 
    this.dialog.setCancelable(false);


}
@Override
protected Object doInBackground(String... params) {

ArrhomePageModelFinal=new ArrayList<HomePageModel>();


    //First time start 0 else:10


 
    Log.e("inside", "First");
//    
try{

HttpClient clientTech = new DefaultHttpClient();
HttpPost request = new HttpPost(Constantz.getRows);




   String json = "";
  // Log.e("inside", "json"+params[0]+params[1]+params[2]+params[3]);
   // 3. build jsonObject
   if(params[0].equalsIgnoreCase("First")){
    Log.e("1nd", "1nd");
    jsonObject = new JSONObject();
   jsonObject.accumulate("param", params[1]);
   jsonObject.accumulate("start", 0);
   jsonObject.accumulate("noofrows", 10);



   }//first
   
   else{
    Log.e("2nd", "2nd");
    //2nd time start: from saved data, else:10
    jsonObject = new JSONObject();
    jsonObject.accumulate("param", params[1]);
   jsonObject.accumulate("start",  params[2]);
   jsonObject.accumulate("noofrows", 10);
 
   }
   // 4. convert JSONObject to JSON to String
   json = jsonObject.toString();
 
   Log.e("inside", "json"+json);
 
// 5. set json to StringEntity
   StringEntity se = new StringEntity(json);
   Log.e("inside", "se"+se);
// 6. set httpPost Entity
   request.setEntity(se);
   // 7. Set some headers to inform server about the type of the content
   request.setHeader("Accept", "application/json");
   request.setHeader("Content-type", "application/json");
 
// request.setEntity(new StringEntity(toPass) );
HttpResponse responseTech = clientTech.execute(request);

Log.e("test","Login:"+responseTech);
String jsonResponse = EntityUtils.toString(responseTech.getEntity());

Log.e("jsonResponse","jsonResponse:"+jsonResponse);
JSONObject reader = new JSONObject(jsonResponse);
Log.e("reader","reader:"+reader);
JSONObject sys  = reader.getJSONObject("response");
Log.e("response","response:"+sys);
jsonArraydata=sys.getJSONArray("data");

ArrhomePageModel=new ArrayList<HomePageModel>();
   if(params[0].equalsIgnoreCase("First")){
   
    Log.e("First", "First");
    needloading=true;
for(int i=0;i<jsonArraydata.length();i++)
{
jsobj=jsonArraydata.getJSONObject(i);
homePageModel=new HomePageModel();
homePageModel.id=jsobj.optString("id");
homePageModel.date_added=jsobj.optString("date_added");
homePageModel.agent=jsobj.optString("agent");
homePageModel.testi=jsobj.optString("testi");
homePageModel.name=jsobj.optString("name");
homePageModel.company=jsobj.optString("company");



ArrhomePageModel.add(homePageModel);


}//for
//
//jsonArrayres reading
   }
   //2nd time
   else{
Log.e("2nd","2nd:");

    ArrhomePageModelsnd=new ArrayList<HomePageModel>();

for(int i=0;i<jsonArraydata.length();i++)
{
jsobj=jsonArraydata.getJSONObject(i);
homePageModel=new HomePageModel();
homePageModel.id=jsobj.optString("id");
homePageModel.date_added=jsobj.optString("date_added");
homePageModel.agent=jsobj.optString("agent");
homePageModel.testi=jsobj.optString("testi");
homePageModel.name=jsobj.optString("name");
homePageModel.company=jsobj.optString("company");



ArrhomePageModelsnd.add(homePageModel);

}//for
//
if(jsonArraydata.length()==0)
{
needloading=false;
Log.e("3needloading", "needloading"+needloading);
}
else{
needloading=true;
}
FileInputStream fis;
try {
fis = context.openFileInput(Constantz.MENA_DATA_OFF+params[1]);
ObjectInputStream is = new ObjectInputStream(fis);

ArrhomePageModel = (ArrayList<HomePageModel>) is.readObject();
Log.e("2nd","2nd:"+ArrhomePageModel.size());

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrhomePageModel.addAll(ArrhomePageModelsnd);
Log.e("2nd","2nd: 2nd"+ArrhomePageModel.size());

   }//else

 

   }//try
 catch (UnsupportedEncodingException exception) {
errorMessage = exception.getMessage();
} catch (ClientProtocolException e) {
errorMessage = e.getMessage();
// e.printStackTrace();
} catch (ConnectTimeoutException e) {
errorMessage = "Time Out!";
//e.printStackTrace();
} catch (UnknownHostException e) {
errorMessage = "No Connection Available!";
//e.printStackTrace();
} catch (Exception e) {
errorMessage = "No Connection Available!";
//e.printStackTrace();
}

if (errorMessage == null) {
Log.e("errorMessage", "errorMessage 7"+errorMessage);
try {
FileOutputStream fos;
fos = context.openFileOutput(Constantz.MENA_DATA_OFF+params[1], Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(ArrhomePageModel);
os.close();
} catch (FileNotFoundException e) {
errorMessage = e.getMessage();
} catch (IOException e) {
errorMessage = e.getMessage();
}
}
else
{
Log.e("param", "param 8");
FileInputStream fis;
try {
fis = context.openFileInput(Constantz.MENA_DATA_OFF+params[1]);
ObjectInputStream is = new ObjectInputStream(fis);

ArrhomePageModel = (ArrayList<HomePageModel>) is.readObject();
Log.e("ArrhomePageModel","ArrhomePageModel final:"+ArrhomePageModel.size());

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
return ArrhomePageModel;

}
@Override
protected void onPostExecute(Object result) {
if (dialog.isShowing()) {
          dialog.dismiss();
      }

callback.onVideoLoadingComplete(errorMessage, result,needloading);

}
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

package com.technomobs.backdoing;

import java.util.HashMap;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.technomobs.Interfacez.RegistrationCompleteInterface;
import com.technomobs.Interfacez.TestimonilCompleteInterface;
import com.technomobs.Utils.Constantz;

public class TestimonilFormSendingLoading extends AsyncTask<String, Void, String> {
ProgressDialog dialog;

//ArrayList<QuestModel> questions;
HashMap<String, String> promoHash;
private String errorMessage=null;
private Context context;
static JSONArray jsonArray; String result;
TestimonilCompleteInterface callback;
String MobileUserID;
public TestimonilFormSendingLoading(Context context, TestimonilCompleteInterface promo) {
this.callback=promo;
this.context=context;

Log.e("inside","gallery");
// TODO Auto-generated constructor stub
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog= new ProgressDialog(context);
this.dialog.setMessage("Please wait..");
    this.dialog.show();
    this.dialog.setCancelable(false);
    Log.e("inside", "gallery");


}
@Override
protected String doInBackground(String... params) {

http://www.mena-properties.com/mena_app/mobilemanager/uploadData/


try{

HttpClient httpclient  = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Constantz.UpLoadData);

    String json = "";
   // Log.e("inside", "json"+params[0]+params[1]+params[2]+params[3]);
    // 3. build jsonObject
    JSONObject jsonObject = new JSONObject();
    jsonObject.accumulate("p", "addtestimonial");
    jsonObject.accumulate("TestimonialUserName", ""+params[0]);
    jsonObject.accumulate("TestimonialPlace", ""+params[1]);
    jsonObject.accumulate("TestimonialComments", ""+params[2]);
    // 4. convert JSONObject to JSON to String
    json = jsonObject.toString();
    StringEntity se = new StringEntity(json);
    httppost.setEntity(se);
    httppost.setHeader("Accept", "application/json");
    httppost.setHeader("Content-type", "application/json");
HttpResponse responseTech = httpclient.execute(httppost);
//    
String jsonResponse = EntityUtils.toString(responseTech.getEntity());

Log.e("test","Login:"+jsonResponse);
JSONObject jobj=new JSONObject(jsonResponse);

JSONObject jsonArray=jobj.getJSONObject("response");

result=jsonArray.optString("status");

       if(result.equalsIgnoreCase("success"))
       {
      result="Testimonials added successfully";
           errorMessage="" ;

       }
       else{
      result="No connection available";
      errorMessage="No connection available" ;
       }

}
catch(Exception e)
{
            errorMessage="No connection available" ;
        result="No connection available";

}







return result;

}
@Override
protected void onPostExecute(String result) {
if (dialog.isShowing()) {
          dialog.dismiss();
      }


callback.onTestimonilCompleteInterface(errorMessage, result);

}
}


Wednesday, 24 September 2014

How to Make Android Map Scrollable Inside a ScrollView Layout

package com.technomobs.Utils;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.google.android.gms.maps.SupportMapFragment;

public class MyMapFragment extends SupportMapFragment {
private OnTouchListener mListener;

    @Override
    public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle savedInstance) {
        View layout = super.onCreateView(layoutInflater, viewGroup, savedInstance);

        TouchableWrapper frameLayout = new TouchableWrapper(getActivity());

        frameLayout.setBackgroundColor(getResources().getColor(android.R.color.transparent));

        ((ViewGroup) layout).addView(frameLayout,
                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        return layout;
    }

    public void setListener(OnTouchListener listener) {
    mListener = listener;
    }

    public interface OnTouchListener {
    public abstract void onTouch();
    }

    public class TouchableWrapper extends FrameLayout {

      public TouchableWrapper(Context context) {
        super(context);
      }

      @Override
      public boolean dispatchTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
          case MotionEvent.ACTION_DOWN:
         mListener.onTouch();
                break;
          case MotionEvent.ACTION_UP:
         mListener.onTouch();
                break;
        }
        return super.dispatchTouchEvent(event);
      }
    }
}

...............................................

Then  create layout using following code


<?xml version="1.0" encoding="UTF-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/sv_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <!-- other child views //-->
     <fragment
        android:tag="fragment_map"
       android:id="@+id/fragment_map"
       android:layout_width="match_parent"
       android:layout_height="175dp"
       android:layout_marginTop="@dimen/activity_horizontal_margin"
       class="com.technomobs.Utils.MyMapFragment"/>
</ScrollView>

.................................


Inside map activity that uses the map,



package com.technomobs.main;
import com.technomobs.Utils.MyMapFragment ;
import com.google.android.gms.maps.GoogleMap;
import android.widget.ScrollView;

public class MyMapActivty extends MapActivity {
    private ScrollView mScrollView;
    private GoogleMap mMap;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.fragment_my_map);

        mMap = ((MyMapFragment ) getSupportFragmentManager().findFragmentById(R.id.fragment_map)).getMap();
        mScrollView = (ScrollView) findViewById(R.id.sv_container);

       ((MyMapFragment ) getSupportFragmentManager().findFragmentById(R.id.fragment_map)).setListener(new WorkaroundMapFragment.OnTouchListener() {
          @Override
          public void onTouch() {
              mScrollView.requestDisallowInterceptTouchEvent(true);
          }
     });
   }
}

Sunday, 21 September 2014

Check EditText View Empty or Not in Android

public class Util
{


public static boolean isEmpty(EditText etText) {
   if (etText.getText().toString().trim().length() > 0) {
       return false;
   } else {
       return true;
   }
}


}


..........................


public class MainActivity
  extends Activity
{

EditText sample;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_createaccount);
sample=(EditText)findViewById(R.id.sample);
if(Util.emailValidator(sample)){
                                                // edittext box empty
                                                      }
                                                        else{



                                                         }

Hide Keyboard in android

public class Util
{


public static void onHideKeyboard(Activity context)
{
try{
InputMethodManager imm = (InputMethodManager) context
           .getSystemService(Context.INPUT_METHOD_SERVICE);

   if (imm.isAcceptingText()) {
     
    imm.hideSoftInputFromWindow(context.getCurrentFocus().getWindowToken(), 0);
   } else {
       //Log.e("Software Keyboard was not shown","no");
   }
}catch(Exception e)
{

}
}

}


..........................


Call in Activity

String name="abcd@gmail.com";

public class MainActivity
  extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_createaccount);


//Hide Keyboard in android
Util.onHideKeyboard(MainActivity.this);


}

}

email Validation in Android

public class Util
{


public static boolean emailValidator(String email)
{
   Pattern pattern;
   Matcher matcher;
   final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
   pattern = Pattern.compile(EMAIL_PATTERN);
   matcher = pattern.matcher(email);
   return matcher.matches();
}


}


..........................


Call in Activity

public class MainActivity
  extends Activity
{

String emailSample="abcd@gmail.com"
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
if(Util.emailValidator(emailSample)){
                                                // email format is correct
                                                      }
                                                        else{

                                                         }


}

}


Set Font in android

publi class Util{
public static void setFont(TextView textview, String font) {

Typeface myTypeface = Typeface.createFromAsset(textview.getContext().getAssets(), font);
textview.setTypeface(myTypeface);

}

}
........................................................

In side Activity Class the following code

put HelveticaNeue-Medium.ttf font type into assets

assets->create folder fonts ->HelveticaNeue-Medium.ttf


TextView name=(TextView)findViewById(R.id.name);
//set font
Util.setFont(name, "fonts/HelveticaNeue-Medium.ttf");

Network Availability check in Android

public static boolean isNetworkAvailable(Context act) {
        ConnectivityManager connectivityManager
              = (ConnectivityManager) act.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null;
    }

if(isNetworkAvailable(MainActivity.this)
{
//connection avilable
}
else{
//no connection

}

GPS Tracker in Android

class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

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

        return location;
    }
   
    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }    
    }
   
    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }
       
        // return latitude
        return latitude;
    }
   
    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }
       
        // return longitude
        return longitude;
    }
   
    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }
   
    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
     
        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");
 
        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
 
        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
//                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
//                mContext.startActivity(intent);
            }
        });
 
        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });
 
        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
   
   
   
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

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

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

}



...............................................

Calling in Activity


GPSTracker gPSTracker;

        gPSTracker=new GPSTracker(getActivity());
//Locate current location
if (gPSTracker.canGetLocation())
{
stringLatitude = String.valueOf(gPSTracker.getLatitude());
stringLongitude = String.valueOf(gPSTracker.getLongitude());
//String place=gPSTracker.getLocality(getApplicationContext());
Double locationLatitude=Double.parseDouble(stringLatitude);
Double locationLongitude=Double.parseDouble(stringLongitude);
}

Thursday, 3 April 2014

To provide animation to each radio button in a radioburron  group in android.

Here I am creating  RadioGroup Dynamicaly
int numAnswer=5;
RadioGroup radioGroupd=new RadioGroup(getApplicationContext());
                int numAnswer=Integer.valueOf(questions.get(showedNum).questions_answers_count);
                for(int i=0;i<numAnswer;i++)
                {
                    button=new  RadioButton(getApplicationContext());
                    button.setTextColor(Color.GREEN);
                    button.setId(i);
                    button.setTextSize(subtextSize);
                    button.setText(questions.get(showedNum).answer_list[i]);
                    radioGroupd.addView(button);
                }
             //imp  
                radioGroupd.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
                {
                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        // TODO Auto-generated method stub
/
                     int id=   group.getCheckedRadioButtonId();//get id
                        RadioButton b = (RadioButton) findViewById(id);
                                   b.startAnimation(myanimateItems);
                    }
                  
                });

How can I add Animation to RadioGroup in android

To provide animation to each radio button in a radioburron  group in android.

Here I am creating  RadioGroup Dynamicaly
int numAnswer=5;
RadioGroup radioGroupd=new RadioGroup(getApplicationContext());
                int numAnswer=Integer.valueOf(questions.get(showedNum).questions_answers_count);
                for(int i=0;i<numAnswer;i++)
                {
                    button=new  RadioButton(getApplicationContext());
                    button.setTextColor(Color.GREEN);
                    button.setId(i);
                    button.setTextSize(subtextSize);
                    button.setText(questions.get(showedNum).answer_list[i]);
                    radioGroupd.addView(button);
                }
             //imp  
                radioGroupd.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
                {
                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        // TODO Auto-generated method stub
/
                     int id=   group.getCheckedRadioButtonId();//get id
                        RadioButton b = (RadioButton) findViewById(id);
                                   b.startAnimation(myanimateItems);
                    }
                  
                });

Thursday, 3 January 2013

TimePicker View in Android

The TimePicker view enables users to select a time of the day, in either 24 Hour mode or AM/PM mode.For this you can use "android.widget.TimePicker" class in android.

You can create TimePicker View using <TimePicker> xml element like this -
 <TimePicker
        android:id="@+id/timePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
       

The TimePicker view displays a standard UI to enable user to set a time. By default, it displays time in the AM/PM format. If you want to change time in the 24 hour format, then you can use the setIs24HourView() method. There are two other important methods of TimePicker -
  • getCurrentHour()
  • getCurrentMinute()
Please note that getCurrentHour() method always returns the hour in 24-hour format i.e. value from 0 to 23.
   

activity_main.xml

(res/layout/activity_main.xml)


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

      <TimePicker
        android:id="@+id/timePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="
Display Time" />
 </LinearLayout>
 

 
TimePickerDemoActivity
(File: TimePickerDemoActivity.java)

package com.example.timepickerdemosimple;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TimePicker;
import android.widget.Toast;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
   
    TimePicker timepicker;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        timepicker = (TimePicker) findViewById(R.id.timePicker);
        timepicker.setIs24HourView(true);
       
      
        // Button View
       Button button = (Button) findViewById(R.id.btn);
       button.setOnClickListener(new View.OnClickListener() {
       
     //   @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
       
        Toast.makeText(getBaseContext(),"Time Selected : "+timepicker.getCurrentHour()+":"
                +timepicker.getCurrentMinute(), Toast.LENGTH_SHORT).show();

        }
    });
    }


Output