Monday, July 22, 2013

Android Quiz timer task example


Android Quiz timer task example

Ex. application for 4 questions and answers with time period, 
Each question having 30 sec time to answer, if not answer show an alert your time up, when user click OK shift to next question.
When user answer the question show the next question with reset the time period.
user can allow to increase the timer for each click 30 sec. 

Please check the bellow code snippet for reference.

   


QuizTimerActivity.Java:
------------------------

package com.example.test;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

public class QuizTimerActivity extends Activity {
private Context mContext;
private int TIME = 30, remaining_sec = 0;
private CountDownTimer countDownTimer;
private TextView textView_timer, currentqusView;
private int totalQus = 4, currentQus = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.timer_layout);
        mContext = this;
textView_timer = (TextView) findViewById(R.id.textView);
currentqusView = (TextView) findViewById(R.id.currentqus);
}

public void getStart(View view){
currentqusView.setText("Current Question: "+currentQus);
TIME = 30;
timerTask();
}

public void getStop(View view){
if(countDownTimer!= null){
countDownTimer.cancel();
countDownTimer = null;
}
}

public void getReStart(View view){
currentQus = 1;
currentqusView.setText("Current Question: "+currentQus);
TIME = 30;
timerTask();
}

public void getIncrease(View view){
TIME = remaining_sec + 30;
timerTask();
}

public void getAns1(View view){
if(countDownTimer!= null){
countDownTimer.cancel();
countDownTimer = null;
}
if(currentQus < totalQus){
currentQus = currentQus + 1;
currentqusView.setText("Current Question: "+currentQus);
TIME = 30;
timerTask();
}
}
public void getAns2(View view){
if(countDownTimer!= null){
countDownTimer.cancel();
countDownTimer = null;
}
if(currentQus < totalQus){
currentQus = currentQus + 1;
currentqusView.setText("Current Question: "+currentQus);
TIME = 30;
timerTask();
}
}

public void getAns3(View view){
if(countDownTimer!= null){
countDownTimer.cancel();
countDownTimer = null;
}
if(currentQus < totalQus){
currentQus = currentQus + 1;
currentqusView.setText("Current Question: "+currentQus);
TIME = 30;
timerTask();
}
}

public void getAns4(View view){
if(countDownTimer!= null){
countDownTimer.cancel();
countDownTimer = null;
}
if(currentQus < totalQus){
currentQus = currentQus + 1;
currentqusView.setText("Current Question: "+currentQus);
TIME = 30;
timerTask();
}
}

public void dialogAlert(String message){
AlertDialog.Builder adb = new AlertDialog.Builder(mContext);
        adb.setTitle(R.string.app_name);
        adb.setMessage(message);
        adb.setNeutralButton("OK",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog,int which) {
                    currentQus = currentQus + 1;
                    currentqusView.setText("Current Question: "+currentQus);
                TIME = 30;
                timerTask();
                        dialog.cancel();
                    }
                });
        AlertDialog ad = adb.create();
        ad.show();
}

public void timerTask(){
if(countDownTimer!= null){
countDownTimer.cancel();
countDownTimer = null;
}
countDownTimer =  new CountDownTimer(TIME * 1000, 1000) {
            public void onTick(long millisUntilFinished) {
          remaining_sec = (int) millisUntilFinished/1000;
          textView_timer.setText(""+remaining_sec);
          System.out.println("TIME---" + TIME + "remaining_sec---" + remaining_sec);
            }
            public void onFinish() {
            TIME = 0;
            dialogAlert("Time finished");
            }
         }.start();
}
}



timer_layout.xml:
------------------


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

    <LinearLayout
        android:id="@+id/scroll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ffffff"
        android:orientation="vertical" >
       
        <TextView
            android:id="@+id/currentqus"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Current Question : ?"
            android:textColor="#000000"
            android:textSize="30sp" />

        <TextView
            android:id="@+id/textView"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Your Time here"
            android:gravity="center"
            android:textColor="#000000"
            android:textSize="30sp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dp" >

            <Button
                android:id="@+id/button5"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="getAns1"
                android:layout_weight="1"
                android:text="Ans1" />

            <Button
                android:id="@+id/button6"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="getAns2"
                android:layout_weight="1"
                android:text="Ans2" />

            <Button
                android:id="@+id/button7"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="getAns3"
                android:text="Ans3" />

            <Button
                android:id="@+id/button8"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="getAns4"
                android:text="Ans4" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dp" >

            <Button
                android:id="@+id/button2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="getStart"
                android:text="Start" />

            <Button
                android:id="@+id/button1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="getStop"
                android:text="Stop" />

            <Button
                android:id="@+id/button3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="getReStart"
                android:text="ReStart" />

            <Button
                android:id="@+id/button4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="getIncrease"
                android:text="Increase" />
        </LinearLayout>
    </LinearLayout>

</ScrollView>




Saturday, June 15, 2013

An useful CommonMethods like getLatitudeLongitudeFromAddress etc

An useful CommonMethods like getLatitudeLongitudeFromAddress etc

An useful CommonMethods like validateEmail, getAddressFromGeo ......
please use this class and call the methods where you want

ex: CommonMethods.validateEmail(abc@gmail.com);

public class CommonMethods {

public static boolean validateEmail(String email) {
final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile(
         "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
         "\\@" +
         "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
         "(" +
         "\\." +
         "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
         ")+"
     );
try {
return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
   }
   catch( NullPointerException exception ) {
       return false;
   }
}

/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
    /*::  This function get address from geo location (latitude and longitude):*/
    /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
    public static List<Address> getAddressFromGeo(Context context, Double latitude, Double longitude) {
    List<Address> address = null;
    try {
List<Address> addresses = new Geocoder(context, Locale.getDefault()).getFromLocation(latitude, longitude, 1);
address = addresses;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return address;
    }

public static double[] getGPS(Context context) {
    LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(true);

/* Loop over the array backwards, and if you get an accurate location, then break out the loop*/
Location l = null;

for (int i=providers.size()-1; i>=0; i--) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) break;
}

double[] gps = new double[2];
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
}
return gps;
}

public static String getMonth(int month) {
   return new DateFormatSymbols().getMonths()[month-1];
}

/**
* returns the string, the first char uppercase
*
* @param target
* @return
*/
public final static String asUpperCaseFirstChar(final String target) {
   if ((target == null) || (target.length() == 0)) {
       return target;
   }
   return Character.toUpperCase(target.charAt(0))
           + (target.length() > 1 ? target.substring(1) : "");
}

public static String convertURL(String str) {
   String url = null;
   try{
   url = new String(str.trim().replace(" ", "%20").replace("&", "%26")
           .replace(",", "%2c").replace("(", "%28").replace(")", "%29")
           .replace("!", "%21").replace("=", "%3D").replace("<", "%3C")
           .replace(">", "%3E").replace("#", "%23").replace("$", "%24")
           .replace("'", "%27").replace("*", "%2A").replace("-", "%2D")
           .replace(".", "%2E").replace("/", "%2F").replace(":", "%3A")
           .replace(";", "%3B").replace("?", "%3F").replace("@", "%40")
           .replace("[", "%5B").replace("\\", "%5C").replace("]", "%5D")
           .replace("_", "%5F").replace("`", "%60").replace("{", "%7B")
           .replace("|", "%7C").replace("}", "%7D"));
   }catch(Exception e){
       e.printStackTrace();
   }
   return url;
}

public static Address getLatitudeLongitudeFromAddress(Context context, String addressval, String zipcode) {
Geocoder coder = new Geocoder(context);
List<Address> address;
Log.d("address",addressval );
try {
if(!zipcode.equals("") && !zipcode.equals("null") && !zipcode.equals(null)) {
address = coder.getFromLocationName(zipcode, 5);
} else {
address = coder.getFromLocationName(addressval,5);
System.out.println("address" + address.get(0) );
}
   if (address != null && !address.isEmpty()) {
   Address location = address.get(0);
   location.getLatitude();
   location.getLongitude();
   return location;
   } else
    return null;
} catch(Exception e) {
e.printStackTrace();
}
return null;
}

public static Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
        int width = bm.getWidth();
        int height = bm.getHeight();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // CREATE A MATRIX FOR THE MANIPULATION
        Matrix matrix = new Matrix();
        // RESIZE THE BIT MAP
        matrix.postScale(scaleWidth, scaleHeight);


        // RECREATE THE NEW BITMAP
        Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
        return resizedBitmap;
    }

public static Bitmap ShrinkBitmap(String file, int width, int height){  
        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
        bmpFactoryOptions.inJustDecodeBounds = true;
        Bitmap bitmap   = BitmapFactory.decodeFile(file, bmpFactoryOptions);
       
        int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)height);
        int widthRatio  = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)width);
       
        if (heightRatio > 1 || widthRatio > 1){
           if (heightRatio > widthRatio){
            bmpFactoryOptions.inSampleSize = heightRatio;
           }else {
         bmpFactoryOptions.inSampleSize = widthRatio;
           }
        }        
        bmpFactoryOptions.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
        return bitmap;
    }

public static String getPath(Uri uri, Activity activity) {
   String[] projection = { MediaStore.Images.Media.DATA };
   Cursor cursor = activity.managedQuery(uri, projection, null, null, null);
   int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
   cursor.moveToFirst();
   return cursor.getString(column_index);
}

/**
* Gets the last image id from the media store
* @return
*/
public static String getLastImageId(Activity activity) {
   final String[] imageColumns = { MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA };
   final String imageOrderBy = MediaStore.Images.Media._ID+" DESC";
   Cursor imageCursor = activity.managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns, null, null, imageOrderBy);
   if(imageCursor.moveToFirst()){
       int id = imageCursor.getInt(imageCursor.getColumnIndex(MediaStore.Images.Media._ID));
       String fullPath = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
       Log.d("Camera", "getLastImageId::id " + id);
       Log.d("Camera", "getLastImageId::path " + fullPath);
       imageCursor.close();
       return fullPath;
   } else {
       return "";
   }
}

public static String getFileExtension(String url) {
int slashIndex = url.lastIndexOf('/');
int dotIndex = url.lastIndexOf('.', slashIndex);
String filenameWithoutExtension = "";
if (dotIndex == -1)
{
 filenameWithoutExtension = url.substring(slashIndex + 1);
}
else
{
 filenameWithoutExtension = url.substring(slashIndex + 1, dotIndex);
}
return filenameWithoutExtension;
}

public static boolean checkImageExtension(String extension) {
String[] exten = {"bmp", "dds", "dng", "gif", "jpg", "png", "psd", "pspimage", "tga", "thm", "jpeg", "yuv"};
for (String val : exten) {
   if (extension.toLowerCase().contains(val)) {
    return true;
   }
}
return false;
}

public static boolean checkFileExtension(String extension) {
String[] exten = {"doc", "docx", "log", "msg", "odt", "pages", "rtf", "tex", "txt", "wpd", "wps"};
for (String val : exten) {
   if (extension.toLowerCase().contains(val)) {
    return true;
   }
}
return false;
}

//CommonMethods
public static double distance(double lat1, double lon1, double lat2, double lon2) {
     double theta = lon1 - lon2;
     double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
     dist = Math.acos(dist);
     dist = rad2deg(dist);
     dist = dist * 60 * 1.1515;
     return (dist);
}

public static double distFrom(double lat1, double lng1, double lat2,
double lng2) {
double earthRadius = 6371;
double dLat = Math.toRadians(lat2 - lat1);
double dLng = Math.toRadians(lng2 - lng1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(lat1))
* Math.cos(Math.toRadians(lat2)) * Math.sin(dLng / 2)
* Math.sin(dLng / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double dist = earthRadius * c;

//Log.d("dist: " , ""+ dist + "--" + lat1 +"," + lng1 +  "--" + lat2 +"," + lng2 );
return (dist);

}

public static float metresToMiles(float metres) {

return (float) (metres * 0.000621371192);
}

public static float metresToKm(float metres) {

return (float) (metres * 0.001);
}

public static float Round(float Rval, int Rpl) {
float p = (float) Math.pow(10, Rpl);
Rval = Rval * p;
float tmp = Math.round(Rval);
return (float) tmp / p;
}
public static double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
    }
public static double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
    }

public static JSONObject getLocationInfo(String address) {

HttpGet httpGet = new HttpGet("http://maps.google."
+ "com/maps/api/geocode/json?address=" + address
+ "ka&sensor=false");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();

try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}

JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
e.printStackTrace();
}

return jsonObject;
}

public static GeoPoint getGeoPoint(JSONObject jsonObject) {
double lon = 0.0;
Double lat = 0.0;
try {
lon = ((JSONArray)jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lng");
lat = ((JSONArray)jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lat");
} catch (JSONException e) {
e.printStackTrace();
}

return new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6));

}


}

Android replace FRENCH characters to English characters

Android replace FRENCH characters to English characters
String french = "Tapez les mots français ici ............";
String english =slugify(french);

public  String slugify(String name) {
String[] hel=name.split("(?!^)");

for(int i=0;i<hel.length;i++){
if(hel[i].contains("é")||hel[i].contains("è")||hel[i].contains("à")||hel[i].contains("ù")||hel[i].contains("â")
||hel[i].contains("ê")||hel[i].contains("î")||hel[i].contains("ô")||hel[i].contains("û")||hel[i].contains("ë")
||hel[i].contains("ï")||hel[i].contains("ç")||hel[i].contains("æ")||hel[i].contains("œ")||hel[i].contains("ü")
||hel[i].contains("À")||hel[i].contains("Â")||hel[i].contains("Æ")||hel[i].contains("Ç")
||hel[i].contains("È")||hel[i].contains("É")||hel[i].contains("Ê")||hel[i].contains("Ë")||hel[i].contains("Î")
||hel[i].contains("Ï")||hel[i].contains("Ô")||hel[i].contains("Œ")||hel[i].contains("Ù")||hel[i].contains("Û")||hel[i].contains("Ü")){
name=name.replace("é", "e");
name=name.replace("è", "e");
name=name.replace("à", "a");
name=name.replace("ù", "u");
name=name.replace("â", "a");
name=name.replace("ê", "e");
name=name.replace("î", "i");
name=name.replace("ô", "o");
name=name.replace("û", "u");
name=name.replace("ë", "e");
name=name.replace("ï", "i");
name=name.replace("ç", "c");
name=name.replace("æ", "ae");
name=name.replace("œ", "oe");
name=name.replace("ü", "u");

name=name.replace("À", "A");
name=name.replace("Â", "A");
name=name.replace("Æ", "AE");
name=name.replace("Ç", "C");
name=name.replace("È", "E");
name=name.replace("É", "E");
name=name.replace("Ê", "E");
name=name.replace("Ë", "E");
name=name.replace("Î", "I");
name=name.replace("Ï", "I");
name=name.replace("Ô", "O");
name=name.replace("Œ", "OE");
name=name.replace("Ù", "U");
name=name.replace("Û", "U");
name=name.replace("Ü", "U");
}
}


String subjectString = "öäü";
        subjectString = Normalizer.normalize(subjectString, Normalizer.Form.NFD);
        String resultString = subjectString.replaceAll("[^\\x00-\\x7F]", "");
        System.out.println(resultString);
       
        String s = "Papier, produit de pâte à papier, non précisé";
        String r = s.replaceAll("\\P{InBasic_Latin}", "");
        System.out.println("-----------"+r);