Friday, February 27, 2015

ANDROID code to read a text file from a raw folder

1)
InputStream is = getResources().openRawResource(R.raw.data);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = br.readLine();
while (line != null) {
     line + = line;
}
System.out.println(line);

2)
Scanner scan = new Scanner(getResources().openRawResource(R.raw.data));
sc.useDelimiter(",");
try {
    while (scan.hasNext()) {
        String word = scan.next();       
    }
} finally {
    scan.close();
}

Wednesday, February 25, 2015

ANDROID code to show Notification



    int NOTIF_ID = 9;

     protected void showNotification(String Spelling) {
        
        Context context = getApplicationContext();
        NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
       
        long when = System.currentTimeMillis();
        Notification notification = new Notification(R.drawable.genera36, "Times to read Spellings", when);
   
        Intent notificationIntent = new Intent(this, TodaysSpellingsActivity.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
   
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0,notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        notification.setLatestEventInfo(context,"Spelling: "+Spelling, "",contentIntent);
        notification.defaults |= Notification.DEFAULT_SOUND;
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        nm.notify(NOTIF_ID++, notification);
    }

ANDROID code to create Shortcut Icon of App

Add Permisssion
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />   

private void createShortcut() {
        Log.d(CLASS, "Method called createShortcut()");

        SharedPreferences prefs = getApplicationContext().getSharedPreferences(
                "shortcut_created", 0);
        SharedPreferences.Editor editor = prefs.edit();
        if (!prefs.getBoolean("shortcut_created", false)) {
            Intent shortcutIntent = new Intent(getApplicationContext(),
                    WelcomeActivity.class);
            shortcutIntent.setAction(Intent.ACTION_MAIN);
            Intent addIntent = new Intent();
            addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
            addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "rVoc");
            addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
                    Intent.ShortcutIconResource.fromContext(
                            getApplicationContext(),
                            R.drawable.rvoc_img));
            addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
            getApplicationContext().sendBroadcast(addIntent);
            editor.putBoolean("shortcut_created", true);
            editor.commit();
            Log.e(CLASS, "Short Created Successfully");
        } else {
            Log.e(CLASS, "Shorrt Cut not created");
        }
    }

ANDROID code Hide Soft Keyboard

        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

ANDROID common method to open particular Activity

protected void openActivity(Class classs) {
        Log.d(CLASS,"Open Activity: "+classs.getSimpleName());
        Intent intent = new Intent(getApplicationContext(), classs);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();               
     }

ANDROID code to show confirmation Dialog

private void showConfirmationDialog() {
         AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(AddNewPurchaseActivity.this);

        alertDialogBuilder.setTitle("TITLE");
        alertDialogBuilder
        .setMessage("MESSAGE ")
        .setCancelable(true)
        .setPositiveButton("No",new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int id) {
                openActivity(MainWelcomeActivity.class);           
             }
          })
        .setNegativeButton("Yes",new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int id) {               
                openActivity(ABCActivity.class);
            }
        });
       
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
       
        Button yes = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
        yes.setBackgroundDrawable(getResources().getDrawable(R.color.xprarkgray));
        yes.setTextColor(Color.WHITE);

        Button no = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
        no.setBackgroundDrawable(getResources().getDrawable(R.color.SeaGreen));
        no.setTextColor(Color.WHITE);
    }

ANDROID code to show date select Dialog

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_DIALOG_ID:
            // set date picker as current date
            return new DatePickerDialog(this, datePickerListener, year, month-1, day);
        }
        return null;
    }   
   
    private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

        // when dialog box is closed, below method will be called.
        public void onDateSet(DatePicker view, int selectedYear,
                int selectedMonth, int selectedDay) {
            year = selectedYear;
            month = selectedMonth;
            day = selectedDay;
            String dayZero="", monthZero="";
            if(day<10){
                dayZero = "0";
            }
           
            if(month<9){
                monthZero = "0";
            }
           
            // set selected date into textview
            etDate.setText(new StringBuilder().append(dayZero+day)
                .append("-").append(monthZero+(month+1)).append("-").append(year).append(" "));

            // set selected date into datepicker also
            dpDate.init(year, month, day, null);

        }
    };   
   

ANDROID code to create PI Chart

package com.raj.er.activities;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.raj.er.R;
import com.raj.er.constants.EApplicationConstants;
import com.raj.er.dao.DAO;
import com.raj.er.report.ChartReportAdapter;
import com.raj.er.report.ReportAdapter;
import com.raj.er.utility.PersonalManagerUtility;

public class PiChartActivity extends Activity {
   
    private static final String CLASS = ViewDatesReportActivity.class.getSimpleName();
    private float expenses[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    private String[] categories = {};
    private DAO dao = null;
    private ListView     categoryListView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pi_charts);
       
        categoryListView = (ListView) findViewById(R.id.lvCategoriesList);
        dao = new DAO(this);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
       
        AdView adView = (AdView) this.findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder()
         .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
         .addTestDevice("").build();
        adView.loadAd(adRequest);
       
        Bundle rcvBag = getIntent().getBundleExtra(EApplicationConstants.ARGUMENTS.getValue());
        String datesValues = (String) rcvBag.getCharSequence(EApplicationConstants.VALUE.getValue());
        String header = (String) rcvBag.getCharSequence(EApplicationConstants.REPORT_HEADER.getValue());
        this.setTitle(header);
       
        getAllCategoriesExpenses(datesValues);
       
        ChartReportAdapter adapter = new ChartReportAdapter(this, categories);
        categoryListView.setAdapter(adapter);

       
        LinearLayout lv1 = (LinearLayout) findViewById(R.id.linear);

        expenses = calculateData(expenses);
        MyGraphview graphview = new MyGraphview(this, expenses);
        lv1.addView(graphview);
       
    }
   
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        switch (item.getItemId()) {
        
        case R.id.menuShareApp:
            shareApp();
            break;
           
        case R.id.menuAbout:
            Intent intent = new Intent(getApplicationContext(), AboutActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            break;
          }
        return super.onOptionsItemSelected(item);
    }
   
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.topmenu, menu);
        return super.onCreateOptionsMenu(menu);
    }
   

    private void shareApp() {
        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, PersonalManagerUtility.getAppSubject());
        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, PersonalManagerUtility.getAppUrlWithMsg());
        startActivity(Intent.createChooser(sharingIntent, "Share via"));       
    }


    private float[] calculateData(float[] data) {
        float total = 0;
        for (int i = 0; i < data.length; i++) {
            total += data[i];
        }
        for (int i = 0; i < data.length; i++) {
            data[i] = 360 * (data[i] / total);
        }
        return data;
    }

    public class MyGraphview extends View {
       
        private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        private float[] value_degree;
        RectF rectf = new RectF(60, 20, 420, 400);
        float temp = 0;
       
        public MyGraphview(Context context, float[] values) {
            super(context);
       
            int totalCategories = dao.getCategories().size();
            value_degree = new float[totalCategories];
            for (int i = 0; i < values.length; i++) {
                value_degree[i] = values[i];
            }
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            int colors[] = new int[20];

            colors[0] = getContext().getResources().getColor(R.color.chartyellow);
            colors[1] = getContext().getResources().getColor(R.color.chartgreen);
            colors[2] = getContext().getResources().getColor(R.color.chartblue);
            colors[3] = getContext().getResources().getColor(R.color.chartred);
            colors[4] = getContext().getResources().getColor(R.color.chartpopati);
            colors[5] = getContext().getResources().getColor(R.color.chartdarkblue);
            colors[6] = getContext().getResources().getColor(R.color.chartorange);
            colors[7] = getContext().getResources().getColor(R.color.chartgray);
            colors[8] = getContext().getResources().getColor(R.color.chartpink);
            colors[9] = getContext().getResources().getColor(R.color.chartblack);
            colors[10] = getContext().getResources().getColor(R.color.chartrani);
            colors[11] = getContext().getResources().getColor(R.color.xpmati);
            colors[12] = getResources().getColor(R.color.xprani);
            colors[13] = getResources().getColor(R.color.xpslate);
            colors[14] = getResources().getColor(R.color.xppopati);
            colors[15] = getResources().getColor(R.color.xpmagenta);
            colors[16] = getResources().getColor(R.color.xpchokolate);
            colors[17] = getResources().getColor(R.color.xpsteelyellow);
            colors[18] = getResources().getColor(R.color.YellowGreen);
            colors[19] = getResources().getColor(R.color.xpabout);
            
            int totalValues = value_degree.length;
            Random r;
            for (int i = 0; i < value_degree.length; i++) {
                if (i == 0) {
                    //r = new Random();
                    //int color = Color.argb(100, r.nextInt(256), r.nextInt(256), r.nextInt(256));
                    paint.setColor(colors[0]);
                    canvas.drawArc(rectf, 0, value_degree[i], true, paint);
                } else {
                    temp += value_degree[i - 1];
                    //r = new Random();
                    //int color = Color.argb(255, r.nextInt(256), r.nextInt(256), r.nextInt(256));
                    if(totalValues<=colors.length){
                        paint.setColor(colors[i]);
                    } else{
                        r = new Random();
                        int color = Color.argb(255, r.nextInt(256), r.nextInt(256), r.nextInt(256));
                        paint.setColor(color);
                    }
                    canvas.drawArc(rectf, temp, value_degree[i], true, paint);
                }
            }
        }
    }
   
    public void getAllCategoriesExpenses(String datesValues){
       
        Log.i(CLASS,"Method called getAllCategoriesExpenses()");
        //String thisMonthDates = PersonalManagerUtility.getMonthDates(PersonalManagerUtility.getCurrentMonthOfYear()-1, PersonalManagerUtility.getCurrentYear());

        dao =  new DAO(this);       
        List<String> rows = new ArrayList<String>(0);
 
        List<String> catList = dao.getCategories();
        for(String categoryName: catList){
            List<String> categoryRows = new ArrayList<String>(0);
            List<String>    tempRows = dao.getCategoryWiseData(datesValues, categoryName);                       
            categoryRows.addAll(tempRows);
            rows.addAll(categoryRows);
        }
       
        expenses = new float[rows.size()];
        categories = new String[rows.size()+1];
        int totalExpense = 0;
       
        for(String row:rows){
            String array[] = row.split("&");                               
            float expense = (array[1]==null ? 0 : Float.parseFloat(array[1]));
            totalExpense += expense;
        }
       
        int i = 0;
        for(String row:rows){
            String array[] = row.split("&");;                   
            float expense = (array[1]==null ? 0 : Float.parseFloat(array[1]));
            double pertFlt = ((expense*100)/totalExpense);
            Log.d(CLASS,"pertFlt------->> "+pertFlt);
            DecimalFormat twoDForm = new DecimalFormat("#.##");
            double percentage =  Double.valueOf(twoDForm.format(pertFlt));
            Log.d(CLASS,"percentage------->> "+percentage);
            categories[i] = array[0]+" ("+array[1]+""+PersonalManagerUtility.getCurrency()+")& "+percentage+"%";
            expenses[i++] = expense;
        }
        categories[i] = "Total ("+totalExpense+""+PersonalManagerUtility.getCurrency()+")& 100%";
       
    }

    public void setReportData(List<String> rows){
        Log.i(CLASS,"Method called setReportData()");
         String[]  values = new String[rows.size()];
        
        int i=0;
        for(String row:rows){
            values[i]=row;
            i++;
        }
       
        ReportAdapter adapter = new ReportAdapter(this, values);
        /*itemList.setAdapter(adapter);
        tvScreenName.setText(reportHeader);
        if(PersonalManagerUtility.getCurrency()==null || PersonalManagerUtility.getCurrency().equalsIgnoreCase("RUPEES")){
            tvTotalExpValue.setText(getResources().getString(R.string.rs)+" "+dao.getTotalPrice());
        }else{
            tvTotalExpValue.setText(PersonalManagerUtility.getCurrency()+" "+dao.getTotalPrice());
        }*/

        //tvTotalExpValue.setText(getResources().getString(R.string.rs)+" "+dao.getTotalPrice());
    }
}

ANDROID code to create BroadcastReceiver to get Battery Information

    private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context arg0, Intent batteryStatus) {
            currentLevel = batteryStatus.getIntExtra("level", 0);
   
            lv1 = (LinearLayout) findViewById(R.id.linear);
            lv1.refreshDrawableState();
            lv1.removeAllViews();
           
            int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
           
            isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;
            String chargineType = "";
            if (isCharging == true && isMsgDisp == false) {
                isMsgDisp = true;
                 int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
                boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
                boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
}


}

ANDROID code to create SPLASH screen

public class SplashScreenActivity extends Activity {
   
    private final int SPLASH_SCREEN_TIME = 1000;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splashscreen_activity);
        //splashScreenHandler.sendEmptyMessageDelayed(0, SPLASH_SCREEN_TIME);
       
        new Handler().postDelayed(new Runnable(){
            @Override
            public void run() {
                Intent mainIntent = new Intent(SplashScreenActivity.this,MainActivity.class);
                SplashScreenActivity.this.startActivity(mainIntent);
                SplashScreenActivity.this.finish();
            }
        }, SPLASH_SCREEN_TIME);
    }        
}

ANDROID code to share Image

    public void shareImage() {
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.setType("image/*");
       
        ArrayList<Uri> files = new ArrayList<Uri>();
        //ClipboardManager obj = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        //ClipData clipData =  null;
        for(String imageName : selectdImages ) {
            //File file = new File("android.resource://com.raj.pics/drawable/"+ getResources().getIdentifier(imageName, "drawable",getPackageName()));
            Uri uri = Uri.parse("android.resource://com.raj.pics/drawable/"+ getResources().getIdentifier(imageName, "drawable",getPackageName()));
            //clipData =  ClipData.newUri(getContentResolver(), "Image", uri);
            //obj.setPrimaryClip(clipData);
            files.add(uri);
        }

        shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, files);
        //shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
        shareIntent.putExtra(Intent.EXTRA_TEXT, "");
        startActivity(Intent.createChooser(shareIntent, "Send your image"));

    }

ANDROID get location info using GPS

public 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

    private static final String CLASS = GPSTracker.class.getSimpleName();

    // 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;
                if (isNetworkEnabled) {
                    Log.d(CLASS,"NetworkEnabled is true--------->>");
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                                                            MIN_TIME_BW_UPDATES,
                                                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                  
                    Log.d("Network", "Network enabled");
                    if (locationManager != null) {
                        Log.d(CLASS,"locationManager--------->>"+locationManager);
                        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            Log.d(CLASS,"location--------->>"+location);
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }else{
                    Log.d(CLASS,"NETWORK ENABLED--------->>FALSE");
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    Log.d(CLASS,"GPS ENABLED--------->>TRUE");
                    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) {
                            Log.d(CLASS,"GPS locationManager--------->>"+locationManager);
                            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            Log.d(CLASS,"GPS location--------->>"+location);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }else{
                    Log.d(CLASS,"GPS ENABLED--------->>FALSE");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            Log.e(CLASS,"Errow while getting location information: "+e.getMessage());
        }

        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;
    }

}

ANDROID code to get all install Apps Information

    private void readAllApps(){
       
            //ArrayList<PInfo> res = new ArrayList<PInfo>();       
            List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
            for(int i=0;i<packs.size();i++) {               
                PackageInfo p = packs.get(i);
               
                if ( p.versionName == null) {
                    continue ;
                }
               
               
                String name = p.applicationInfo.loadLabel(getPackageManager()).toString()+" "+p.versionName;
                /*if(name.contains("com.android")){
                    continue;
                }*/
               
                FileData fileData = new FileData();               
                fileData.setName(name);
                fileData.setPath(p.packageName);
               
                //newInfo.versionName = p.versionName;
                if(isSystemPackage(p)==true){
                    fileData.setType(EApplicationConstant.Default.val());
                    sysAppsNamesList.add(fileData);
                    //sysAppsNamesList.add(name + EApplicationConstant.DataSeparator.val() + p.packageName);
                }else{
                    fileData.setType(EApplicationConstant.Apps.val());
                    //appsNamesList.add(name + EApplicationConstant.DataSeparator.val() + p.packageName);
                    appsNamesList.add(fileData);
                }
               
                //PInfo newInfo = new PInfo();
                /*newInfo.appname = p.applicationInfo.loadLabel(getPackageManager()).toString();
                newInfo.pname = p.packageName;
                newInfo.versionName = p.versionName;
                newInfo.versionCode = p.versionCode;
                newInfo.icon = p.applicationInfo.loadIcon(getPackageManager());
                res.add(newInfo);*/
            }
     }

ANDROID code to get all Contacts information

    private void readContacts() {

        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
                null, null, null);
        String phone = null;
        // String emailContact = null;
        // String emailType = null;
        // String image_uri = "";
        // Bitmap bitmap = null;
        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {
                String id = cur.getString(cur
                        .getColumnIndex(ContactsContract.Contacts._ID));
                String name = cur
                        .getString(cur
                                .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

                /*
                 * image_uri = cur .getString(cur
                 * .getColumnIndex(ContactsContract
                 * .CommonDataKinds.Phone.PHOTO_URI));
                 */
                if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                    // System.out.println("name : " + name + ", ID : " + id);
                    // sb.append(name+" "+id);
                    Cursor pCur = cr.query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                    + " = ?", new String[] { id }, null);
                    while (pCur.moveToNext()) {
                        phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        // sb.append(" " + phone);
                        // System.out.println("phone" + phone);
                    }
                    pCur.close();
                    StringBuilder pn = new StringBuilder();
                    for (char ch : phone.toCharArray()) {
                        if (ch == ' ' || ch == '\n') {
                        } else {
                            pn.append(ch);
                        }
                    }
                    FileData fileData = new FileData();
                    fileData.setName(name);
                    fileData.setPath(pn.toString());
                    fileData.setType(EApplicationConstant.Contact.val());
                    contactsList.add(fileData);
                    /*contactsList.add(name
                            + EApplicationConstant.DataSeparator.val() + " "
                            + pn.toString());*/

                    // sb.toString()

                    /*
                     * Cursor emailCur = cr.query(
                     * ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                     * ContactsContract.CommonDataKinds.Email.CONTACT_ID +
                     * " = ?", new String[] { id }, null); while
                     * (emailCur.moveToNext()) { emailContact = emailCur
                     * .getString(emailCur
                     * .getColumnIndex(ContactsContract.CommonDataKinds
                     * .Email.DATA)); emailType = emailCur .getString(emailCur
                     * .getColumnIndex
                     * (ContactsContract.CommonDataKinds.Email.TYPE));
                     * sb.append("\nEmail:" + emailContact + "Email type:" +
                     * emailType); System.out.println("Email " + emailContact +
                     * " Email Type : " + emailType);
                     *
                     * }
                     */

                    // emailCur.close();
                }

                /*
                 * if (image_uri != null) {
                 * System.out.println(Uri.parse(image_uri)); try { bitmap =
                 * MediaStore.Images.Media .getBitmap(this.getContentResolver(),
                 * Uri.parse(image_uri)); sb.append("\n Image in Bitmap:" +
                 * bitmap); System.out.println(bitmap);
                 *
                 * } catch (FileNotFoundException e) { // TODO Auto-generated
                 * catch block e.printStackTrace(); } catch (IOException e) { //
                 * TODO Auto-generated catch block e.printStackTrace(); }
                 *
                 * }
                 */

                // sb.append("\n........................................");
            }

            // textDetail.setText(sb);
        }
    }

ANDROID code to show progress dialog

       ProgressDialog  progressDialog = new ProgressDialog(this);       
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Please Wait....");
        progressDialog.setIndeterminate(true);
        progressDialog.setCancelable(true);
        progressDialog.show();

ANDROID + read sql file and execute queries

WelcomeActivity.java

 public class WelcomeActivity extends Activity {

  @Override
    public void onCreate(Bundle bundle) {

           super.onCreate(bundle);
           setContentView(R.layout.welcome);
 

           DAO dao = new DAO(this);

             dao.openConnection();
            Log.i(CLASS, "Reading create_tables.sql file");
            InputStream sqlFile = getResources().openRawResource(R.raw.tables);
            dao.readSQlFile(sqlFile);
            dao.closeConnection();

       }
}

DAO.java

public class DAO extends SQLiteOpenHelper {

     private SQLiteDatabase sqliteDatabase;

    public DAO(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    public void openConnection() throws SQLException {

        sqliteDatabase = this.getWritableDatabase();
    }

    public void readSQlFile(InputStream is) {

        String fileData = "";
        try {
            int i;
            while ((i = is.read()) != -1) {
                fileData += (char) i;
            }
        } catch (Exception ex) {
            Log.e(CLASS,
                    "Exception while reading SQL file, Reason: "
                            + ex.getMessage());
        } finally {
            getSQLQueries(fileData);
        }
    }

    public boolean executeQuery(String query) {
        Log.d(CLASS, "Method called executeQuery()");
        boolean flag = false;
        try {
            openConnection();
            sqliteDatabase.execSQL(query);
            flag = true;
        } catch (Exception ex) {
            Log.d(CLASS,
                    "Error while executing quwey, Reason: " + ex.getMessage());
            flag = false;
        } finally {
            closeConnection();
        }
        return flag;
    }

    public void getSQLQueries(String fileData) {

        //Log.i(CLASS, "Method called getSQLQueries()");
        if (fileData != null && fileData.trim().length() > 0) {
            String[] sqlQueries = fileData.split(";");
            for (String query : sqlQueries) {
                Log.d(CLASS, "Query : " + query);
                if (query != null && query.trim().length() > 0) {
                    sqliteDatabase.execSQL(query);
                    //Log.d(CLASS, "Query executed successfully");
                } else {
                    //Log.d(CLASS, "Empty Query");
                }
            }
        }

    }

    public void closeConnection() {
        this.close();
        //Log.i(CLASS, "Method called closeDB()\nDatabase closed succesfully.");
    }

    public SQLiteDatabase getSQLiteDB() {
        return sqliteDatabase;
    }

}
 

tables.sql (put in raw folder)

CREATE TABLE IF NOT EXISTS  SPELLING_DATA
(
    SRNO NUMERIC(6),
    SPELLING VARCHAR(50),
    EMEANING VARCHAR(50),
    HMEANING VARCHAR(50),
    USAGE VARCHAR(100),
    DISPLAY_STATUS VARCHAR(4),
    PARAM1 VARCHAR(10),
    PARAM2 VARCHAR(10),
    PRIMARY KEY (SPELLING)
);


CREATE TABLE IF NOT EXISTS  EXAM_DATA
(
    SRNO NUMERIC(6),
    EXAM_DATE_TIME TIMESTAMP,
    EXAM_RESULT_GRADE VARCHAR(2),
    TOTAL_SPELL VARCHAR(2),
    TOTAL_TRUE VARCHAR(2),
    TOTAL_FALSE VARCHAR(2),
    PARAM1 VARCHAR(2),
    PARAM2 VARCHAR(2),
    PRIMARY KEY (EXAM_DATE_TIME)
);


Keep Visiting

Monday, February 2, 2015

HOW TO ADD INPUT BOX IN A DISPLAYED ALERTDIALOG

AlertDialog.Builder dialogBox = new AlertDialog.Builder(this);

dialogBox.setTitle("My App Name");
dialogBox.setMessage("Enter username");

// Adding EditText box into the dialog
final EditText etUsername = new EditText(this);
dialogBox.setView(input);
// you can set the further property of the EditText here 

dialogBox.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
  String username = etUsername.getText().toString();
// logic on the username value
  }
});

dialogBox.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
  public void onClick(DialogInterface dialog, int whichButton) {
     // logic if user click on the cancel button
  }
});

dialogBox.show();